(PHP 4, PHP 5, PHP 7, PHP 8)
print — Muestra un string
Muestra expression.
print no es una función sino una construcción del lenguaje.
Su argumento es la expresión que sigue a la palabra clave print,
y no está delimitado por paréntesis.
La diferencia principal con echo es que
print solo acepta un argumento y siempre devuelve 1.
expression
La expresión a mostrar. Los valores que no son strings serán convertidos a string,
incluso si la directiva
strict_types está activada.
Devuelve 1, siempre.
Ejemplo #1 Ejemplo con print
<?php
print "print no requiere paréntesis.";
print PHP_EOL;
// No se añade salto de línea ni espacio; lo siguiente se muestra como "helloworld" en una sola línea
print "hello";
print "world";
print PHP_EOL;
print "Este string abarca
múltiples líneas. Los saltos de línea también
se mostrarán";
print PHP_EOL;
print "Este string abarca\nmúltiples líneas. Los saltos de línea\nse mostrarán también.";
print PHP_EOL;
// El argumento puede ser cualquier expresión que produzca un string
$foo = "example";
print "foo es $foo"; // foo es example
print PHP_EOL;
$fruits = ["lemon", "orange", "banana"];
print implode(" y ", $fruits); // lemon y orange y banana
print PHP_EOL;
// Las expresiones no-string son convertidas a string, incluso si se usa declare(strict_types=1)
print 6 * 7; // 42
print PHP_EOL;
// Como print tiene un valor de retorno, puede ser usado en expresiones
// Lo siguiente muestra "hello world"
if ( print "hello" ) {
echo " world";
}
print PHP_EOL;
// Lo siguiente muestra "true"
( 1 === 1 ) ? print 'true' : print 'false';
print PHP_EOL;
?>Nota: Uso con paréntesis
Rodear el argumento de
<?php print "hello"; // muestra "hello" print("hello"); // también muestra "hello", porque ("hello") es una expresión válida print(1 + 2) * 3; // muestra "9"; los paréntesis hacen que 1+2 se evalúe primero, luego 3*3 // la sentencia print ve toda la expresión como un argumento if ( print("hello") && false ) { print " - dentro de if"; } else { print " - dentro de else"; } // muestra " - dentro de if" // la expresión ("hello") && false se evalúa primero, dando false // esto se convierte al string vacío "" y se muestra // la construcción print luego devuelve 1, por lo que se ejecuta el código en el bloque if ?>Cuando
<?php if ( (print "hello") && false ) { print " - dentro de if"; } else { print " - dentro de else"; } // muestra "hello - dentro de else" // a diferencia del ejemplo anterior, la expresión (print "hello") se evalúa primero // después de mostrar "hello", print devuelve 1 // como 1 && false es false, se ejecuta el código en el bloque else print "hello " && print "world"; // muestra "world1"; print "world" se evalúa primero, // luego la expresión "hello " && 1 se pasa al print de la izquierda (print "hello ") && (print "world"); // muestra "hello world"; los paréntesis fuerzan a que las expresiones print // se evalúen antes del && ?>
Nota: Como esto es una estructura del lenguaje, y no una función, no es posible llamarla con las funciones variables o argumentos nombrados.
Be careful when using print. Since print is a language construct and not a function, the parentheses around the argument is not required.
In fact, using parentheses can cause confusion with the syntax of a function and SHOULD be omited.
Most would expect the following behavior:
<?php
if (print("foo") && print("bar")) {
// "foo" and "bar" had been printed
}
?>
But since the parenthesis around the argument are not required, they are interpretet as part of the argument.
This means that the argument of the first print is
("foo") && print("bar")
and the argument of the second print is just
("bar")
For the expected behavior of the first example, you need to write:
<?php
if ((print "foo") && (print "bar")) {
// "foo" and "bar" had been printed
}
?>The other major difference with echo is that print returns a value, even it’s always 1.
That might not look like much, but you can use print in another expression. Here are some examples:
<?php
rand(0,1) ? print 'Hello' : print 'goodbye';
print PHP_EOL;
print 'Hello ' and print 'goodbye';
print PHP_EOL;
rand(0,1) or print 'whatever';
?>
Here’s a more serious example:
<?php
function test() {
return !!rand(0,1);
}
test() or print 'failed';
?>I wrote a println function that determines whether a \n or a <br /> should be appended to the line depending on whether it's being executed in a shell or a browser window. People have probably thought of this before but I thought I'd post it anyway - it may help a couple of people.
<?php
function println ($string_message) {
$_SERVER['SERVER_PROTOCOL'] ? print "$string_message<br />" : print "$string_message\n";
}
?>
Examples:
Running in a browser:
<?php println ("Hello, world!"); ?>
Output: Hello, world!<br />
Running in a shell:
<?php println ("Hello, world!"); ?>
Output: Hello, world!\n