print

(PHP 4, PHP 5, PHP 7, PHP 8)

printMuestra un string

Descripción

print(string $expression): int

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.

Parámetros

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.

Valores devueltos

Devuelve 1, siempre.

Ejemplos

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;
?>

Notas

Nota: Uso con paréntesis

Rodear el argumento de print con paréntesis no generará un error de sintaxis, y produce una sintaxis similar a una llamada normal de función. No obstante, esto puede ser engañoso, ya que los paréntesis forman en realidad parte de la expresión que se está mostrando, y no parte de la sintaxis de print en sí mismo.

<?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 print se usa en una expresión más grande, colocar tanto la palabra clave como su argumento entre paréntesis puede ser necesario para obtener el resultado esperado:

<?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: Puesto que esto es una construcción del lenguaje y no una función, no puede ser llamada usando funciones variables.

Ver también

add a note

User Contributed Notes 3 notes

up
30
user at example dot net
16 years ago
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
}
?>
up
6
mark at manngo dot net
1 year ago
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';
?>
up
16
danielxmorris @ gmail dotcom
17 years ago
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
To Top