print

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

printAffiche une chaîne de caractères

Description

print(string $expression): int

Affiche expression.

print n'est pas une fonction mais une construction du langage. Son argument est l'expression suivant le mot clé print, et n'est pas délimité par des parenthèses.

La différence majeure avec echo est que print n'accepte qu'un seul argument et retourne toujours 1.

Liste de paramètres

expression

L'expression à afficher. Les valeurs qui ne sont pas des chaînes de caractères seront converties en celle-ci, même si la directive strict_types est activée.

Valeurs de retour

Retourne 1, toujours.

Exemples

Exemple #1 Exemple avec print

<?php
print "print does not require parentheses.";
print
PHP_EOL;

// Aucune nouvelle ligne ou espace n'est ajoutée ; ci-dessous affiche "helloworld", tout sur une ligne
print "hello";
print
"world";
print
PHP_EOL;

print
"This string spans
multiple lines. The newlines will be
output as well"
;
print
PHP_EOL;

print
"This string spans\nmultiple lines. The newlines will be\noutput as well.";
print
PHP_EOL;

// L'argument peut être n'importe quelle expression qui produit une chaîne de caractères
$foo = "example";
print
"foo is $foo"; // foo is example
print PHP_EOL;

$fruits = ["lemon", "orange", "banana"];
print
implode(" and ", $fruits); // lemon and orange and banana
print PHP_EOL;

// Les expressions qui ne sont pas des chaînes sont converties en chaînes, même si declare(strict_types=1) est utilisé
print 6 * 7; // 42
print PHP_EOL;

// Parce que print a une valeur de retour, il peut être utilisé dans des expressions
// Le code suivant affiche "hello world"
if ( print "hello" ) {
echo
" world";
}
print
PHP_EOL;

// Le code suivant affiche "true"
( 1 === 1 ) ? print 'true' : print 'false';
print
PHP_EOL;
?>

Notes

Note: Utilisation avec des parenthèses

Entourer l'argument de print avec des parenthèses ne lèvera pas une erreur de syntaxe, et produit une syntaxe ressemblant à un appel normal de fonction. Néanmoins, ceci peut être trompeur, car les parenthèses font en réalité partie de l'expression qui est en cours d'affichage, et non partie de la syntaxe de print en lui-même.

<?php
print "hello";
// affiche "hello"

print("hello");
// affiche également "hello", car ("hello") est une expression valide

print(1 + 2) * 3;
// affiche "9" ; les parenthèses permettent à 1+2 d'être évalué en premier, puis 3*3
// l'instruction print voit l'expression entière comme un seul argument

if ( print("hello") && false ) {
print
" - inside if";
}
else {
print
" - inside else";
}
// affiche " - inside if"
// l'expression ("hello") && false est d'abord évaluée, donnant false
// celle-ci est convertie en chaîne vide "" et affichée
// la construction print retourne alors 1, donc le code du bloc if est exécuté
?>

Quand print est utilisé dans une expression plus large, placer tous deux le mot clé et son argument dans les parenthèses peut être nécessaire pour obtenir le résultat attendu :

<?php
if ( (print "hello") && false ) {
print
" - inside if";
}
else {
print
" - inside else";
}
// affiche "hello - inside else"
// contrairement à l'exemple précédent, l'expression (print "hello") est évaluée en premier
// après avoir affiché "hello", print retourne 1
// puisque 1 && false vaut false, le code du bloc else est exécuté

print "hello " && print "world";
// affiche "world1" ; print "world" est évalué en premier,
// puis l'expression "hello " && 1 est passée au print de gauche

(print "hello ") && (print "world");
// affiche "hello world" ; les parenthèses forcent les expressions print
// à être évaluées avant le &&
?>

Note: Comme ceci est une structure du langage, et non pas une fonction, il n'est pas possible de l'appeler avec les fonctions variables ou arguments nommés.

Voir aussi

add a note

User Contributed Notes 3 notes

up
31
user at example dot net
17 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
14
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
up
2
mark at manngo dot net
2 years 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';    
?>
To Top