downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | conferences | my php.net

search for in the

explode> <crypt
[edit] Last updated: Fri, 17 May 2013

view this page in

echo

(PHP 4, PHP 5)

echoAffiche une chaîne de caractères

Description

void echo ( string $arg1 [, string $... ] )

Affiche tous les paramètres.

echo n'est pas vraiment une fonction (c'est techniquement une structure du langage), cela fait que vous n'êtes pas obligé d'utiliser des parenthèses. echo (contrairement à d'autres structures de langage) ne se comporte pas comme une fonction, il ne peut donc pas être utilisé dans le contexte d'une fonction. De même, si vous voulez passer plusieurs paramètres à echo, les paramètres ne doivent pas être entourés de parenthèses.

echo dispose aussi d'une version courte, où vous pouvez faire suivre la balise PHP ouvrante d'un signe égal (=). Avant PHP 5.4.0, cette syntaxe n'était possible que si la directive de configuration short_open_tag était activée.

J'ai <?=$foo?> foo.

Liste de paramètres

arg1

Le paramètre à afficher.

...

Valeurs de retour

Aucune valeur n'est retournée.

Exemples

Exemple #1 Exemple avec echo

<?php
echo "Bonjour le monde";

echo 
"Cet echo() se
répartit sur plusieurs lignes. Il affiche aussi les
nouvelles lignes"
;

echo 
"Cet echo() se\nrépartit sur plusieurs lignes. Il affiche aussi les\nnouvelles lignes";

echo 
"L'échappement de caractères se fait : \"comme ceci\".";

// Vous pouvez utiliser des variables avec echo()
$foo "foobar";
$bar "barbaz";

echo 
"foo vaut $foo"// foo vaut foobar

// Vous pouvez aussi utiliser des tableaux
$baz = array("value" => "foo");

echo 
"this is {$baz['value']} !"// c'est foo !

// Les guillemets simples annulent le remplacement des variables
echo 'foo vaut $foo'// foo vaut $foo

// Si vous n'utilisez pas d'autres caractères,
// vous pouvez afficher plusieurs variables
// en les séparant par des virgules
echo $foo;          // foobar
echo $foo,$bar;     // foobarbarbaz

// Des personnes préfèrent passer plusieurs
// paramètres en utilisant la concaténation
echo 'Cette ''chaîne ''a été ''faite ''avec plusieurs paramètres.'chr(10);
echo 
'Cette ' 'chaîne ' 'a été ' 'faite ' 'à l\'aide de la concaténation.' "\n";

echo <<<END
Cette syntaxe s'intitule le "here document" et
permet d'afficher plusieurs lignes avec de
l'interpolation de variables. Notez que la fin de
la syntaxe doit apparaître sur une nouvelle ligne,
avec uniquement un point-virgule, et pas d'espace
de plus !
END;

// parce que echo() ne se comporte pas comme une fonction, le code suivant n'est pas valide.
($some_var) ? echo 'true' : echo 'false';

// Cependant, les lignes suivantes sont valides :
($some_var) ? print 'Oui' : print 'Non'// print est aussi une structure de langage, mais
                                   // il se comporte comme une fonction, donc,
                                   // il peut être utilisé dans ce contexte.
echo $some_var 'Oui''Non';
?>

Notes

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.

Voir aussi



explode> <crypt
[edit] Last updated: Fri, 17 May 2013
 
add a note add a note User Contributed Notes echo - [9 notes]
up
4
nikolaas dot mennega at links dot com dot au
5 years ago
hemanman at gmail dot com, the problem is that func() doesn't actually return a value (string or otherwise), so the result of echoing func() is null.

With the comma version, each argument is evaluated and echoed in turn: first the literal string (simple), then func(). Evaluating a function call obviously calls the function (and in this case executes its own internal echo), and the result (null) is then echoed accordingly. So we end up with "outside func() within func()" as we would expect.

Thus:

<?php
echo "outside func ()\n", func ();
?>

effectively becomes:

<?php
echo "outside func ()\n";
//func ()
{
echo
"within func ()\n";
}
echo
'';
?>

The dot version is different: there's only one argument here, and it has to be fully evaluated before it can be echoed as requested. So we start at the beginning again: a literal string, no problem, then a concatenator, then a function call. Obviously the function call has to be evaluated before the result can be concatenated with the literal string, and THAT has to happen BEFORE we can complete the echo command. But evaluating func() produces its own call to echo, which promptly gets executed.

Thus:

<?php
echo "outside func ()\n" . func ();
?>

effectively becomes:

<?php
//func ()
{
echo
"within func ()\n";
}
echo
"outside func ()\n" . '';
?>
up
1
Sammy Moshe
2 months ago
And if you wanted to, you could do something like
echo "test1","test2","test3";

I'm not sure how it's useful. Might be good if you have a bunch of strings you want to output at once, but it doesn't seem to work with arrays. I'm working on a practical application, but as yet haven't had a need for it.
up
2
Jason Carlson - SiteSanity
8 years ago
In response to Ryan's post with his echobig() function, using str_split wastes memory resources for what you are doing.

If all you want to do is echo smaller chunks of a large string, I found the following code to perform better and it will work in PHP versions 3+

<?php
function echobig($string, $bufferSize = 8192)
{
 
// suggest doing a test for Integer & positive bufferSize
 
for ($chars=strlen($string)-1,$start=0;$start <= $chars;$start += $bufferSize) {
    echo
substr($string,$start,$buffer_size);
  }
}
?>
up
2
ryan at wonko dot com
8 years ago
Due to the way TCP/IP packets are buffered, using echo to send large strings to the client may cause a severe performance hit. Sometimes it can add as much as an entire second to the processing time of the script. This even happens when output buffering is used.

If you need to echo a large string, break it into smaller chunks first and then echo each chunk. The following function will do the trick in PHP5:

<?php
function echobig($string, $bufferSize = 8192)
{
   
$splitString = str_split($string, $bufferSize);

    foreach(
$splitString as $chunk)
        echo
$chunk;
}
?>
up
0
Jakob Thomsen
4 years ago
A way to color your echo output is to use shell_exec and the echo command (this only works on Linux/bash) in the following way:

<?php
echo shell_exec('echo "\e[0;31m Red color \e[0;32mGreen color \e[0m No color "');
?>

See http://wiki.archlinux.org/index.php/Color_Bash_Prompt for more colors and other options.
up
-1
gbarros at yahoo-inc dot com
3 years ago
just banged my head on this missing bits on the manual.
When using the <<< method, the array keys does not require any kind of quotes.

<?php
foreach ( $data as $i ){
echo <<< END
<tr>
  <td>
$i[date]</td>
  <td>
$i[name]</td>
 </tr>
END;
}
?>

Let's hope you don't have any <?php echo $klingonships['th\'bl][ath']?> kind of array :)
up
-2
ximlabz at gmail dot com
1 year ago
A remedy to the problems caused by different management of returns between different platforms you can use the predefined constant PHP_EOF as the second parameter:

<?php
$foo
= "foo";
$bar = "bar";

echo
"Foo is $foo", PHP_EOL;
echo
"Bar is $bar";

// is the same as using:

echo "Foo is $foo\n";
echo
"Bar is $bar";

// but here only for UNIX-like platforms
?>
up
-2
fire at dls dot net
1 year ago
Pay attention to this part of the documentation:
echo() (unlike some other language constructs) does not behave like a function, so it cannot always be used in the context of a function

I was trying to make certain that I was detecting errors and was trying code like this:

@alwaysFails() or echo('Surprise! It failed again');

This error was generated:
[29-Jul-2011 12:56:19] PHP Parse error:  syntax error, unexpected T_ECHO in /Applications/MAMP/test.php on line 12

Changing to die(), print() or a function I defined worked fine. Beware of this limitation of echo.
up
-3
zombie)at(localm)dot(org)
10 years ago
[Ed. Note: During normal execution, the buffer (where echo's arguments go) is not flushed (sent) after each write to the buffer. To do that you'd need to use the flush() function, and even that may not cause the data to be sent, depending on your web server.]

Echo is an i/o process and i/o processes are typically time consuming. For the longest time i have been outputting content by echoing as i get the data to output. Therefore i might have hundreds of echoes in my document. Recently, i have switched to concatenating all my string output together and then just doing one echo at the end. This organizes the code more, and i do believe cuts down on a bit of time. Likewise, i benchmark all my pages and echo seems to influence this as well. At the top of the page i get the micro time, and at the end i figure out how long the page took to process. With the old method of "echo as you go" the processing time seemed to be dependent on the user's net connection as well as the servers processing speed. This was probably due to how echo works and the sending of packets of info back and forth to the user. One an one script i was getting .0004 secs on a cable modem, and a friend of mine in on dialup was getting .2 secs. Finally, to test that echo is slow; I built strings of XML and XSLT and used the PHP sablotron functions to do a transformation and return a new string. I then echoed the string. Before the echo, the process time was around .025 seconds and .4 after the echo. So if you are big into getting the actual processing time of your scripts, don't include echoes since they seem to be user dependent. Note that this is just my experience and it could be a fluke.

 
show source | credits | sitemap | contact | advertising | mirror sites