|
|
 |
echo (PHP 3, PHP 4, PHP 5) echo -- Muestra una o más cadenas Descripciónvoid echo ( string arg1 [, string ...] )
Muestra todos sus parámetros por la salida definida.
echo() no es realmente una función (es una
sentencia del lenguaje) de modo que no se requiere el uso de
los paréntesis. De hecho, si se indica más de un parámetro,
no se pueden incluir los paréntesis.
Ejemplo 1. Ejemplos de echo() |
<?php
echo "Hola Mundo";
echo "Este texto se extiende
por varias lineas. Los saltos de linea
tambien se envian";
echo "Este texto se extiende\npor varias lineas. Los saltos de linea\ntambien se envian.";
echo "Para escapar caracteres, se debe indicar \"de esta forma\".";
$saludo = "que tal";
$despedida = "hasta luego";
echo "hola, $saludo"; $cadena = array("valor" => "saludo desde un array");
echo "Esto es un {$cadena['valor']} "; echo 'hola, $saludo'; echo $saludo; echo $saludo,$despedida; echo 'Esta ', 'cadena ', 'esta ', 'construida ', 'con muchos parametros.', chr(10);
echo 'Esta ' . 'cadena ' . 'esta ' . 'construida ' . 'empleando concatenacion.' . "\n";
echo <<<FIN
Este texto utiliza una sintaxis especial que
permite mostrar varias lineas de texto.
La etiqueta que indica el final del bloque de texto
(y que en este caso es "FIN") debe aparecer en una
linea que contenga solamente el valor de la etiqueta
y un caracter de punto y coma (ni siquiera puede
contener espacios en blanco).
FIN;
($una_variable) ? echo 'verdadero' : echo 'falso';
($una_variable) ? print('verdadero'): print('falso'); echo $una_variable ? 'verdadero': 'false'; ?>
|
|
echo() tambié funciona con una sintaxis abreviada
formada por una etiqueta de apertura seguida de un signo igual.
La sintaxis abreviada solamente funciona si se encuentra habilitada la
directiva de configuración short_open_tag.
En el siguiente articulo de la "FAQTs Knowledge Base" http://www.faqts.com/knowledge_base/view.phtml/aid/1/fid/40
puede encontrarse una argumentación sobre las diferencias
entre las funciones print() y echo().
Nota: Puesto que esto es
una construcción del lenguaje y no una función, no puede
ser llamado usando funciones
variables
See also
print(),
printf(), y
flush().
rwruck
27-Jan-2006 01:15
It should be mentioned here that the script will be aborted if you output something in response to a HTTP HEAD request.
In the following example, the second line will NOT be written to the file. Any registered shutdown function will be called, though:
<?php
$hf = fopen('head.log', 'ab');
fwrite($hf, "before output\n");
echo "Test";
fwrite($hf, "after output\n");
fclose($hf);
?>
This is normal behaviour; see the description of $_SERVER.
lorenpr at gmail dot com
14-Sep-2005 09:12
I hope this ternary thing isn't overkill. Last thing - I would just like to make you aware of the side effect when you do this statement,
echo $some_var ? print 'true': print 'false';
The result would be either 'true1' or 'false1', depending on whether $some_var is true or false respectively. This happens because of what I mentioned earlier. Figure it out.
lorenpr at gmail dot com
14-Sep-2005 08:58
linus is correct.
The ternary relationship is evaluated first, then echo prints the result.
Also, keep in mind
(condition? a : b)
reads
if(condition) return a; else return b;
So what makes
A. echo ($somevar) ? 'true' : 'false';
different from
B. ($somevar) ? echo 'true' : echo 'false';
is the ternary relationship in A reads
if (condition) return 'true'; else return 'false';
while in B it reads
if(condition) return (echo 'true'); else return (echo 'false');
- an invalid statement, since echo evaluates to void.
linus.martensson a gmail
24-Aug-2005 02:03
Simple. it reads like echo (($somevar)?'true';'false'); and outputs the result, unless I'm mistaken.
shannonmoeller at gmail dot com
09-Aug-2005 04:31
In reply to lorenpr at gmail dot com:
If what you say is true, why does this work?
<?php
echo ($somevar) ? 'true' : 'false'; ?>
lorenpr at gmail dot com
28-Jul-2005 10:17
I just want to point out something to beginners. The documentation is misleading where it says:
// Because echo is not a function, following code is invalid.
($some_var) ? echo 'true' : echo 'false';
The code is invalid, but not because 'echo' is a language construct, but rather because 'echo' does not return a value.
So don't be mislead: the syntax used above is certainly not limited to functions.
You must keep in mind that the job of the ternary syntax used is not actually to display anything, but to test a boolean relationship. The 'print' statement would work because it always returns a 1, which in php, is interpreted to a boolean 'true'. Things that return 'void' cannot be expected to evaluate to a 'true' or 'false', and that is why using 'echo' in this particular case is invalid.
Jason Carlson - SiteSanity
16-May-2005 10:28
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)
{
for ($chars=strlen($string)-1,$start=0;$start <= $chars;$start += $bufferSize) {
echo substr($string,$start,$buffer_size);
}
}
?>
renrutal at gmail dot com
28-Mar-2005 03:34
Note that:
<?php
echo "2 + 2 = " . 2+2; echo "2 + 2 = " , 2+2; ?>
The commas will parse the result of the expressions correctly.
ryan at wonko dot com
27-Feb-2005 12:56
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;
}
?>
Truffy
15-Jan-2005 01:02
You can use braces around variables as well as array items. This is useful to help recognition of your variables in your code, but most useful where the variable iteslf cannot be separated with spaces from the preceding/following code, for exmple in a file path:
If a path is assigned the variable $path, then this code will not work:
echo "$pathhttp://indices.com.es/index.html";
whereas this will
echo "{$path}http://indices.com.es/index.html";
zombie)at(localm)dot(org)
25-Jan-2003 11:26
[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.
| |
|
| Chiste de... En el colegio | | Justicia y corrección | En el colegio, el profesor le pregunta a Carlitos:
- Carlitos, ¿tú sabes cuál es la diferencia entre lo justo y lo correcto?
- Verás, te metes el dedo índice en la nariz, te queda justo, pero no es correcto. | | Chistes en tu mail | | ©ContenidosGratis |
| Inicio | Acción | Estrategia | Palabras | Puzzles | Solitarios | Foro Trucos |  | Cake Mania Jugadores: 6835 Categoría del juego: Acción Objetivo del juego: Ayuda a Jill a recuperar la pastelería de su abuela llevando su propia pastelería; consigue clientes y gana dinero. |
|  | Rainbow Web Jugadores: 2199 Categoría del juego: Puzzles Objetivo del juego: Rompe un pegajoso hechizo y salva un reino de fantasía en Rainbow Web. Tendrás toneladas de diversión mientras juegas a este mágico desafío para la mente. |
|  | Mahjongg Fortuna Jugadores: 12462 Categoría del juego: Solitarios Objetivo del juego: Velocidad y habilidad mental son las armas más importantes en esta versión de un antiguo juego asiático. Despeja el tablero lo antes posible haciendo clic en las fichas iguales y gánate la fama eterna de la puntuación más alta. |
|  | Chainz 2 Jugadores: 6955 Categoría del juego: Puzzles Objetivo del juego: Entra en el mundo de las combinaciones con Chainz 2: Relinked, emocionante secuela del exitazo del año pasado, Chainz. Gira eslabones y crea combinaciones de 3 ó más. |
|  | Delicious Jugadores: 4405 Categoría del juego: Acción Objetivo del juego: ¿Eres un as de la multitarea? ¿Quieres que tus clientes estén contentos? ¡Pues Delicious es tu juego! Sacia el apetito de los clientes y tenlos contentos; ¡no te arriesgues! |
|  | Bookworm Jugadores: 4568 Categoría del juego: Palabras Objetivo del juego: Junta las letras para formar palabras. ¡Las palabras más largas valen más puntos! |
|  | Zuma Jugadores: 4976 Categoría del juego: Acción Objetivo del juego: Controla el ídolo de la rana de piedra de los antiguos Zuma en este intrigante enigma de acción. ¡Dispara bolas para formar conjuntos de tres, pero si dejas que lleguen a la calavera dorada morirás! |
|  | Jewel of Atlantis Jugadores: 3798 Categoría del juego: Puzzles Objetivo del juego: Descubre la ciudad hundida de la Atlántida y busca valiosos tesoros. Viaja más allá de las profundidades del mar y vive trepidantes aventuras en Jewel of Atlantis. |
|  | Jewel Quest Jugadores: 3727 Categoría del juego: Puzzles Objetivo del juego: Convierte la arena de la antigua selva en oro tan rápido como puedas juntando grupos de 3 elementos. ¡Los grupos más grandes valen más puntos! |
|  | Bejeweled 2 Jugadores: 3659 Categoría del juego: Puzzles Objetivo del juego: Con cuatro modos de juego únicos y fascinantes, nuevas piezas de juego explosivas e imponentes fondos planetarios, Bejeweled 2 es mucho más adictivo que nunca. |
|
|