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

search for in the

Matrices> <Números de punto flotante
Last updated: Tue, 27 Nov 2007

view this page in

Cadenas

Un valor string es una serie de caracteres. En PHP, un caracter es lo mismo que un byte, es decir, hay exactamente 256 tipos de caracteres diferentes. Esto implica también que PHP no tiene soporte nativo de Unicode. Vea utf8_encode() y utf8_decode() para conocer sobre el soporte Unicode.

Note: El que una cadena se haga muy grande no es un problema. PHP no impone límite práctico alguno sobre el tamaño de las cadenas, así que no hay ninguna razón para preocuparse sobre las cadenas largas.

Sintaxis

Un literal de cadena puede especificarse en tres formas diferentes.

Comillas simples

La forma más simple de especificar una cadena sencilla es rodearla de comillas simples (el caracter ').

Para especificar una comilla sencilla literal, necesita escaparla con una barra invertida (\), como en muchos otros lenguajes. Si una barra invertida necesita aparecer antes de una comilla sencilla o al final de la cadena, necesitará doblarla. Note que si intenta escapar cualquier otro caracter, ¡la barra invertida será impresa también! De modo que, por lo general, no hay necesidad de escapar la barra invertida misma.

Note: En PHP 3, se generará una advertencia de nivel E_NOTICE cuando esto ocurra.

Note: A diferencia de las otras dos sintaxis, las variables y secuencias de escape para caracteres especiales no serán expandidas cuando ocurren al interior de cadenas entre comillas sencillas.

<?php
echo 'esta es una cadena simple';

echo 
'También puede tener saltos de línea embebidos
en las cadenas de esta forma, ya que
es válido'
;

// Imprime: Arnold dijo una vez: "I'll be back"
echo 'Arnold dijo una vez: "I\'ll be back"';

// Imprime: Ha eliminado C:\*.*?
echo 'Ha eliminado C:\\*.*?';

// Imprime: Ha eliminado C:\*.*?
echo 'Ha eliminado C:\*.*?';

// Imprime: Esto no va a expandirse: \n una nueva línea
echo 'Esto no va a expandirse: \n una nueva línea';

// Imprime: Las variables no se $expanden $tampoco
echo 'Las variables no se $expanden $tampoco';
?>

Comillas dobles

Si la cadena se encuentra rodeada de comillas dobles ("), PHP entiende más secuencias de escape para caracteres especiales:

Caracteres escapados
secuencia significado
\n alimentación de línea (LF o 0x0A (10) en ASCII)
\r retorno de carro (CR o 0x0D (13) en ASCII)
\t tabulación horizontal (HT o 0x09 (9) en ASCII)
\v tabulación vertical (VT o 0x0B (11) en ASCII) (desde PHP 5.2.5)
\f alimentación de forma (FF o 0x0C (12) en ASCII) (a partir de PHP 5.2.5)
\\ barra invertida
\$ signo de dólar
\" comilla-doble
\[0-7]{1,3} la secuencia de caracteres que coincide con la expresión regular es un caracter en notación octal
\x[0-9A-Fa-f]{1,2} la secuencia de caracteres que coincide con la expresión regular es un caracter en notación hexadecimal

Nuevamente, si intenta escapar cualquier otro caracter, ¡la barra invertida será impresa también! Antes de PHP 5.1.1, la barra invertida en \{$var} no venía imprimiéndose.

Pero la característica más importante de las cadenas entre comillas dobles es el hecho de que los nombres de variables serán expandidos. Vea procesamiento de cadenas para más detalles.

Heredoc

Otra forma de delimitar cadenas es mediante el uso de la sintaxis heredoc ("<<<"). Debe indicarse un identificador (seguido por un salto de línea) después de la secuencia <<<, luego la cadena, y luego el mismo identificador para cerrar la cita.

El identificador de cierre debe comenzar en la primera columna de la línea. Asimismo, el identificador usado debe seguir las mismas reglas que cualquier otra etiqueta en PHP: debe contener solo caracteres alfanuméricos y de subrayado, y debe iniciar con un caracter no-dígito o de subrayado.

Warning

Es muy importante notar que la línea con el identificador de cierre no contenga otros caracteres, excepto quizás por un punto-y-coma (;). Esto quiere decir en especial que el identificador no debe usar sangría, y no debe haber espacios o tabuladores antes o después del punto-y-coma. Es importante también notar que el primer caracter antes del identificador de cierre debe ser un salto de línea, tal y como lo defina su sistema operativo. Esto quiere decir \r en Macintosh, por ejemplo. El delimitador de cierre (posiblemente seguido de un punto-y-coma) debe ser seguido también por una nueva línea.

Si esta regla es rota y el identificador de cierre no es "limpio", entonces no se considera un identificador de cierre y PHP continuará en busca de uno. Si, en tal caso, no se encuentra un identificador de cierre apropiado, entonces un error del analizador sintáctico resultará con el número de línea apuntando al final del script.

No es permitido usar la sintaxis heredoc al inicializar miembros de clase. Use otro tipo de sintaxis en su lugar.

Example#1 Ejemplo inválido

<?php
class foo {
    public 
$bar = <<<EOT
bar
EOT;
}
?>

El texto heredoc se comporta tal como una cadena entre comillas dobles, sin las comillas dobles. Esto quiere decir que no necesita escapar tales comillas en sus bloques heredoc, pero aun puede usar los códigos de escape listados anteriormente. Las variables son expandidas, aunque debe tenerse el mismo cuidado cuando se expresen variables complejas al interior de un segmento heredoc, al igual que con otras cadenas.

Example#2 Ejemplo de uso de una cadena heredoc

<?php
$cadena 
= <<<FIN
Ejemplo de una cadena
que se extiende por varias líneas
usando la sintaxis heredoc.
FIN;

/* Un ejemplo más complejo, con variables. */
class foo
{
    var 
$foo;
    var 
$bar;

    function 
foo()
    {
        
$this->foo 'Foo';
        
$this->bar = array('Bar1''Bar2''Bar3');
    }
}

$foo = new foo();
$nombre 'MiNombre';

echo <<<FIN
Mi nombre es "$nombre". Estoy imprimiendo algo de $foo->foo.
Ahora, estoy imprimiendo algo de 
{$foo->bar[1]}.
Esto debería imprimir una letra 'A' mayúscula: \x41
FIN;
?>

Note: El soporte heredoc fue agregado en PHP 4.

Procesamiento de variables

Cuando una cadena es especificada en comillas dobles o al interior de un bloque heredoc, las variables son interpretadas en su interior.

Existen dos tipos de sintaxis: una simple y una compleja. La sintaxis simple es la más común y conveniente. Esta ofrece una forma de interpretar una variable, un valor array, o una propiedad de un object.

La sintaxis compleja fue introducida en PHP 4, y puede reconocerse por las llaves que rodean la expresión.

Sintaxis simple

Si un signo de dólar ($) es encontrado, el analizador sintáctico tomará ambiciosamente tantos lexemas como le sea posible para formar un nombre de variable válido. Rodee el nombre de la variable de llaves si desea especificar explícitamente el final del nombre.

<?php
$cerveza 
'Heineken';
echo 
"El sabor de varias $cerveza's es excelente"// funciona, "'" no es un caracter válido para nombres de variables
echo "Tomó algunas $cervezas";   // no funciona, 's' es un caracter válido para nombres de variables
echo "Tomó algunas ${cerveza}s"// funciona
echo "Tomó algunas {$cerveza}s"// funciona
?>

De forma similar, puede hacer que un índice de un array o una propiedad de un object sean interpretados. En el caso de los índices de matrices, el corchete cuadrado de cierre (]) marca el final del índice. Para las propiedades de objetos, se aplican las mismas reglas de las variables simples, aunque con las propiedades de objetos no existe un truco como el que existe con las variables.

<?php
// Estos ejemplos son específicos al uso de matrices al interior de
// cadenas. Cuando se encuentre por fuera de una cadena, siempre rodee
// de comillas las claves tipo cadena de su matriz, y no use
// {llaves} por fuera de cadenas tampoco.

// Mostremos todos los errores
error_reporting(E_ALL);

$frutas = array('fresa' => 'roja''banano' => 'amarillo');

// Funciona pero note que esto trabaja de forma diferente por fuera de
// cadenas entre comillas
echo "Un banano es $frutas[banano].";

// Funciona
echo "Un banano es {$frutas['banano']}.";

// Funciona, pero PHP busca una constante llamada banano primero, como
// se describe más adelante.
echo "Un banano es {$frutas[banano]}.";

// No funciona, use llaves. Esto resulta en un error de análisis sintáctico.
echo "Un banano es $frutas['banano'].";

// Funciona
echo "Un banano es " $frutas['banano'] . ".";

// Funciona
echo "Este cuadro tiene $cuadro->ancho metros de ancho.";

// No funciona. Para una solución, vea la sintaxis compleja.
echo "Este cuadro tiene $cuadro->ancho00 centímetros de ancho.";
?>

Para cualquier cosa más sofisticada, debería usarse la sintaxis compleja.

Sintaxis compleja (llaves)

Esta no es llamada compleja porque la sintaxis sea compleja, sino porque es posible incluir expresiones complejas de esta forma.

De hecho, de esta forma puede incluir cualquier valor que sea parte del espacio de nombres al interior de cadenas. Simplemente escriba la expresión en la misma forma que lo haría si se encontrara por fuera de una cadena, y luego la ubica entre { y }. Ya que no es posible escapar '{', esta sintaxis será reconocida únicamente cuando el caracter $ se encuentra inmediatamente después de {. (Use "{\$" para obtener una secuencia literal "{$"). Algunos ejemplos para aclarar el asunto:

<?php
// Mostremos todos los errores
error_reporting(E_ALL);

$genial 'fantástico';

// No funciona, imprime: Esto es { fantástico}
echo "Esto es { $genial}";

// Funciona, imprime: Esto es fantástico
echo "Esto es {$genial}";
echo 
"Esto es ${genial}";

// Funciona
echo "Este cuadro tiene {$cuadro->ancho}00 centímetros de ancho.";

// Funciona
echo "Esto funciona: {$matriz[4][3]}";

// Esto está mal por la misma razón por la que $foo[bar] está mal por
// fuera de una cadena. En otras palabras, aun funciona pero ya que
// PHP busca primero una constante llamada foo, genera un error de
// nivel E_NOTICE (constante indefinida).
echo "Esto está mal: {$matriz[foo][3]}";

// Funciona. Cuando se usan matrices multi-dimensionales, use siempre
// llaves alrededor de las matrices al interior de cadenas
echo "Esto funciona: {$matriz['foo'][3]}";

// Funciona.
echo "Esto funciona: " $arr['foo'][3];

echo 
"Puede incluso escribir {$obj->valores[3]->nombre}";

echo 
"Este es el valor de la variable llamada $nombre: {${$nombre}}";
?>

Note: Las llamadas a funciones y métodos trabajan a partir de PHP 5.

Note: Interpretar variables al interior de cadenas usa más memoria que la concatenación de cadenas. Cuando escriba un script PHP en el cual el uso de memoria sea de cuidado, considere el uso del operador de concatenación (.) en lugar de la interpolación de variables.

Acceso a cadenas y modificación por caracter

Los caracteres al interior de una cadena pueden ser consultados y modificados al especificar el desplazamiento, comenzando en cero, del caracter deseado después de la cadena usando corchetes cuadrados tipo-matriz como $cadena[42], así que piense en una cadena como un array de caracteres.

Note: También es posible acceder a los caracteres usando llaves como $cadena{42} para el mismo propósito. Sin embargo, se prefiere el uso de corchetes cuadrados ya que el estilo {corchetes} es considerado obsoleto a partir de PHP 6.

Example#3 Algunos ejemplos de cadenas

<?php
// Obtener el primer caracter de una cadena
$cadena 'Esta es una prueba.';
$primer $cadena[0];

// Obtener el tercer caracter de una cadena
$tercer $cadena[2];

// Obtener el Ãºltimo caracter de una cadena.
$cadena 'Esta es también una prueba.';
$ultimo $cadena[strlen($cadena)-1];

// Modificar el Ãºltimo caracter de una cadena
$cadena 'Observe el mar';
$cadena[strlen($cadena)-1] = 'l';

// El método alternativo usando {} es obsoleto desde PHP 6
$tercer $cadena{2};

?>

Note: Al accesar variables de otros tipos mediante [] o {} se devuelve silenciosamente NULL.

Funciones y operadores útiles

Las cadenas pueden ser concatenadas usando el operador '.' (punto). Note que el operador '+' (adición) no funciona para este propósito. Por favor refiérase a la sección Operadores de cadena para más información.

Existen bastantes funciones útiles para la modificación de cadenas.

Vea la sección de funciones de cadena para consultar funciones de uso general, o las funciones de expresiones regulares para búsquedas y reemplazos avanzados (en dos sabores: Perl y POSIX extendido).

Existen también funciones para cadenas tipo URL, y funciones para encriptar/descifrar cadenas (mcrypt y mhash).

Finalmente, si aun no ha encontrado lo que busca, vea también las funciones de tipo de caracter.

Conversión a cadena

Es posible convertir un valor a una cadena usando el moldeamiento (string), o la función strval(). La conversión a cadena se realiza automáticamente para usted en el contexto de una expresión cuando se necesita una cadena. Esto ocurre cuando usa las funciones echo() o print(), o cuando compara el valor de una variable con una cadena. El contenido de las secciones del manual sobre Tipos y Manipulación de Tipos ayudan a aclarar este hecho. Vea también settype().

Un valor boolean TRUE es convertido a la cadena "1", el valor FALSE se representa como "" (una cadena vacía). De esta forma, usted puede convertir de ida y vuelta entre valores booleanos y de cadena.

Un número integer o de punto flotante (float) es convertido a una cadena que representa el número con sus dígitos (incluyendo la parte del exponente para los números de punto flotante).

Note: El caracter de punto decimal es definido en la localización del script (categoría LC_NUMERIC). Vea setlocale().

Las matrices son siempre convertidas a la cadena "Array", de modo que no puede volcar los contenidos de un valor array con echo() o print() para ver lo que se encuentra en su interior. Para ver un elemento, usted tendría que hacer algo como echo $arr['foo']. Vea más adelante algunos consejos sobre el volcado/vista del contenido completo.

Los objetos en PHP 4 son convertidos siempre a la cadena "Object". Si quisiera imprimir los valores de variables miembro de un object para efectos de depuración, lea los parágrafos siguientes. Si quiere conocer el nombre de clase del cual un objeto dado es instancia, use get_class(). A partir de PHP 5, el método __toString() es usado si resulta aplicable.

Los recursos son siempre convertidos a cadenas con la estructura "Resource id #1" en donde 1 es el número único del valor resource asignado por PHP durante tiempo de ejecución. Si quisiera obtener el tipo del recurso, use get_resource_type().

NULL se convierte siempre a una cadena vacía.

Como puede apreciar, el imprimir matrices, objetos o recursos no le ofroce información útil sobre los valores mismos. Consulte las funciones print_r() y var_dump() para conocer mejores formas de imprimir valores para depuración.

También puede convertir valores PHP a cadenas y almacenarlas permanentemente. Este método es conocido como seriación, y puede ser efectuado con la función serialize(). También puede seriar valores PHP a estructuras XML, si cuenta con soporte WDDX en su configuración de PHP.

Conversión de cadenas a números

Cuando una cadena es evaluada como un valor numérico, el valor resultante y su tipo son determinados como sigue.

La cadena será evaluada como un float si contiene cualquier caracter entre '.', 'e', o 'E'. De otra forma, evaluará como un entero.

El valor es dado por la porción inicial de la cadena. Si la cadena comienza con datos numéricos válidos, éstos serán el valor usado. De lo contrario, el valor será 0 (cero). Un signo opcional es considerado un dato numérico válido, seguido por uno o más dígitos (que pueden contener un punto decimal), seguidos por un exponente opcional. El exponente es una 'e' o 'E' seguida de uno o más dígitos.

<?php
$foo 
"10.5";                // $foo es flotante (11.5)
$foo "-1.3e3";              // $foo es flotante (-1299)
$foo "bob-1.3e3";           // $foo es entero (1)
$foo "bob3";                // $foo es entero (1)
$foo "10 Cerditos";         // $foo es entero (11)
$foo "10.2 Cerditos";       // $foo es flotante (14.2)
$foo "10.0 cerdos " 1;        // $foo es flotante (11)
$foo "10.0 cerdos " 1.0;      // $foo es flotante (11)
?>

Para más información sobre esta conversión, vea la página del manual Unix sobre strtod(3).

Si quisiera probar cualquiera de los ejemplos presentados en esta sección, puede cortar y pegar los ejemplos e insertar la siguiente línea para verificar por sí mismo lo que está sucediendo:

<?php
echo "\$foo==$foo; tipo es " gettype ($foo) . "<br />\n";
?>

No espere obtener el código de un caractar convirtiéndolo a un entero (como lo haría en C, por ejemplo). Use las funciones ord() y chr() para convertir entre códigos de caracter y caracteres.



Matrices> <Números de punto flotante
Last updated: Tue, 27 Nov 2007
 
add a note add a note User Contributed Notes
Cadenas
qriz at example dot com
13-Nov-2007 07:54
<?php
$a
= '2007-11-05 15:17:49';
$b = '2007-11-05 15:17:48';

$bool = $a > $b;

var_dump($bool); //bool(true)
?>

works correctly since there is a comparing between strings. The comparisson is done on the last number/letter (since thats the only thing that is difference in the string) and that is in this case: the 9 and 8.

8 > 9 = true

if you want to compare the string as pure numbers then you must type cast it to numbers or type juggle it:

<?php
$a
= '2007-11-05 15:17:49';
$b = '2007-11-05 15:17:48';

$bool1 = ($a + 0) > ($b + 0);      // 2007 > 2007
$bool2 = (int) $a > (int) $b;        // 2007 > 2007
$bool3 = intval($a) > intval($b);  // 2007 > 2007

var_dump($bool1,$bool2,$bool3); //bool(false)
?>
topnotcher at mail dot uri dot edu
06-Nov-2007 02:48
I have come across this several times, and as far as I can tell, the < and > operators have undocumented functionality when it comes to comparing strings.  Consider the following script:

<?php
$a
= '2007-11-05 15:17:49';
$b = '2007-11-05 15:17:48';

$bool = $a > $b;

var_dump($bool); //bool(true)

/**
 * The manual tells us that $a and $b should be
 * truncated at -, thus giving a floating-point value of 2007.
 * But (2007 > 2007) === false...
 */
$a = (float)$a;
$b = (float)$b;

var_dump($a); //float(2007);
var_dump($b); //float(2007);

/**
 * And the manual is right. So why does it correctly
 * compare the dates (which should be treated
 * as normal strings? Clearly some hidden functionality...
 */
php at luyer dot nl
24-Oct-2007 10:20
You can also use a here document as an argument in a function call. Like this:

<?php
foo
(<<<EOT
Example of string
spanning multiple lines
using heredoc syntax.
EOT
);
?>

Note: no semicolon after the EOT (just as when using quoted text)
Kunal Thaggarse
22-Oct-2007 07:41
When saving the output of an HTML table as an excel sheet, avoid using double quoted string literals after the attribute 'width', because the excel sheet won't display the table. 

Example:
<?php
header
("Content-Type:  application/vnd.ms-excel");
echo
"<table border=1 align=center width=95\"%\">";
echo
"<table>";
echo
"<tr><td>abc</td><tr>";
echo
"<tr><td>xyz</td><tr>";
echo
"</table>";
?>

Use "<table border=1 align=center width=95%>" instead.
ktcb123 at hotmail dot com
22-Oct-2007 09:24
For some reason, none of the url_exists() functions posted here worked for me, so here is my own tweaked version of it.

<?php
   
function url_exists($url){
       
$url = str_replace("http://", "", $url);
        if (
strstr($url, "/")) {
           
$url = explode("/", $url, 2);
           
$url[1] = "/".$url[1];
        } else {
           
$url = array($url, "/");
        }

       
$fh = fsockopen($url[0], 80);
        if (
$fh) {
           
fputs($fh,"GET ".$url[1]." HTTP/1.1\nHost:".$url[0]."\n\n");
            if (
fread($fh, 22) == "HTTP/1.1 404 Not Found") { return FALSE; }
            else { return
TRUE;    }

        } else { return
FALSE;}
    }
?>
bluej100@gmail
15-Oct-2007 09:04
The '0e00' == '00' scientific notation strangeness is documented at http://us2.php.net/manual/en/language.operators.comparison.php:

"If you compare two numerical strings, they are compared as integers."

I don't see any documentation for the odd handling of hexadecimal strings, though.

var_dump(intval('0xf')) // int(0)
var_dump((int)'0xf') // int(0)
var_dump(0 + '0xf') // int(15)
var_dump('0xf' == 15) // bool(true)
bluej100@gmail
15-Oct-2007 05:57
This is debatably a bug, and certainly not what I expected:

<?php
var_dump
('00' == '0e99'); // true
var_dump('0e99' == '00'); // true
?>

Basically, any two strings such that each matches /0+([eE]\d+)?/ are equal.
frosty at north-pole dot us
07-Oct-2007 01:31
mouse:
test_double_quote_replace was only faster because it was $a was all contained in a single set of quotes.
mouse at windworld dot ru
30-Sep-2007 05:00
I'm used the following code:

<?php

function test_simple_quote_concat()
{
 
$b = 'string';
 
$a  = ' string'.$b.' string'.$b.' srting'.$b;
 
$a .= ' string'.$b.' string'.$b.' string'.$b;
 
$a .= ' string'.$b.' string'.$b.' string'.$b;
 
$a .= ' string'.$b.' string'.$b.' string'.$b;
 
$a .= ' string'.$b.' string'.$b.' string'.$b;
 
$a .= ' string'.$b.' string'.$b.' string'.$b;
 
$a .= ' string'.$b.' string'.$b.' string'.$b;
 
$a .= ' string'.$b.' string'.$b.' string'.$b;
}

function
test_double_quote_concat()
{
 
$b = "string";
 
$a  = " string".$b." string".$b." string".$b;
 
$a .= " string".$b." string".$b." string".$b;
 
$a .= " string".$b." string".$b." string".$b;
 
$a .= " string".$b." string".$b." string".$b;
 
$a .= " string".$b." string".$b." string".$b;
 
$a .= " string".$b." string".$b." string".$b;
 
$a .= " string".$b." string".$b." string".$b;
 
$a .= " string".$b." string".$b." string".$b;
}

function
test_double_quote_replace()
{
 
$b = "string";
 
$a = " string$b string$b string$b
string
$b string$b string$b
string
$b string$b string$b
string
$b string$b string$b
string
$b string$b string$b
string
$b string$b string$b
string
$b string$b string$b
string
$b string$b string$b";
}

function
test_eot_replace()
{
 
$b = <<<EOT
string
EOT;
 
$a = <<<EOT
string{$b} string{$b} string{$b}
string
{$b} string{$b} string{$b}
string
{$b} string{$b} string{$b}
string
{$b} string{$b} string{$b}
string
{$b} string{$b} string{$b}
string
{$b} string{$b} string{$b}
string
{$b} string{$b} string{$b}
string
{$b} string{$b} string{$b}
EOT;
}

$iter = 100000;

$time_start = microtime(1);

$time_start = microtime(1);
for(
$i=0; $i<$iter; $i++ )
 
test_double_quote_concat();
$duration2 = microtime(1) - $time_start;

$time_start = microtime(1);
for(
$i=0; $i<$iter; $i++ )
 
test_double_quote_replace();
$duration3 = microtime(1) - $time_start;

$time_start = microtime(1);
for(
$i=0; $i<$iter; $i++ )
 
test_eot_replace();
$duration4 = microtime(1) - $time_start;

$time_start = microtime(1);
for(
$i=0; $i<$iter; $i++ )
 
test_simple_quote_concat();
$duration1 = microtime(1) - $time_start;

echo
'simple_quote_concat: '.$duration1." s\n";
echo
'double_quote_concat: '.$duration2." s\n";
echo
'double_quote_replace: '.$duration3." s\n";
echo
'eot_quote_replace: '.$duration4." s\n";
?>

And got very different results. Compare it yourself.
$ php test.php
simple_quote_concat: 0.853082895279 s
double_quote_concat: 0.896748065948 s
double_quote_replace: 0.708463907242 s
eot_quote_replace: 0.735204935074 s
$ php test.php
simple_quote_concat: 0.786070823669 s
double_quote_concat: 0.800376176834 s
double_quote_replace: 0.659599065781 s
eot_quote_replace: 0.674590110779 s
$ php test.php
simple_quote_concat: 0.819690942764 s
double_quote_concat: 0.842829942703 s
double_quote_replace: 0.659816980362 s
eot_quote_replace: 0.756074905396 s
$ php test.php
simple_quote_concat: 0.785160064697 s
double_quote_concat: 0.77215385437 s
double_quote_replace: 0.659204006195 s
eot_quote_replace: 0.67343211174 s
As you can see, simple and double quoted strings very close to each other.
rkfranklin+php at gmail dot com
26-Sep-2007 09:35
If you want to use a variable in an array index within a double quoted string you have to realize that when you put the curly braces around the array, everything inside the curly braces gets evaluated as if it were outside a string.  Here are some examples:

<?php
$i
= 0;
$myArray[Person0] = Bob;
$myArray[Person1] = George;

// prints Bob (the ++ is used to emphasize that the expression inside the {} is really being evaluated.)
echo "{$myArray['Person'.$i++]}<br>";

// these print George
echo "{$myArray['Person'.$i]}<br>";
echo
"{$myArray["Person{$i}"]}<br>";

// These don't work
echo "{$myArray['Person$i']}<br>";
echo
"{$myArray['Person'$i]}<br>";

// These both throw fatal errors
// echo "$myArray[Person$i]<br>";
//echo "$myArray[Person{$i}]<br>";
?>
michael at mahemoff dot com
07-Jul-2007 10:51
Heredocs can be used for more than just echoing or setting variables - use them whenever you want to include a string.

function header() {
  return <<<EOT
    <html>
      <head>
        <title>This is my heredoc</title>
      </head>
      <body>
EOT;

Also, note the strict syntax:
- No semicolon after initial EOT (think of the heredoc as a literal string arg - you wouldn't want a semicolon in front of it, would you?)
- BUT need semicolon after final EOT (the command is finished here)
- Final EOT is on the left margin - don't indent it!
php at craigbuchek dot com
04-Jul-2007 12:32
Function calls within double-quote variable interpolation work in PHP 5, but not quite as you'd expect. Basically the function has to be a variable function. I.e. a variable that holds the name of a function. So if you've got a function named 'x' that you want to call, you'll have to assign the function name to a variable. It's easiest to just assign it to a variable with the same name:

function x () { return 4; }
$x = 'x';
echo "x = {$x()}";

I'm not sure what the point of that is though, since it would be easier to do it this way:

function x () { return 4; }
$x = x();
echo "x = $x";
php at modem-help dot com
03-Jul-2007 06:32
The section `#language.types.string.parsing' above says:

"Before PHP 5.1.1, backslash in \{$var} hasn't been printed."

...but does not inform how to fix that. The answer is easy: double each curly-bracket.

So, when producing inline CSS:

<?php
$hBack
= '#99ccff';
$hFore = '#000088';
$style = "background:$hBack;color:$hFore;"

echo "h1 {background:$hBack;color:$hFore;}
h2 \{
$style}
h3 {
{$style}}";
?>

PHP < v5.1.1 prints:
h1 {background:#99ccff;color:#000088;}
h2 {background:#99ccff;color:#000088;}
h3 {background:#99ccff;color:#000088;}

PHP => v5.1.1 prints:
h1 {background:#99ccff;color:#000088;}
h2 \{background:#99ccff;color:#000088;}
h3 {background:#99ccff;color:#000088;}

Please note: I have not checked `{{$style}}' on PHP before v5.1.1; the assumption seems reasonable.
Richard Neill
01-Jun-2007 06:31
Unlike bash, we can't do
  echo "\a"       #beep!

Of course, that would be rather meaningless for PHP/web, but it's useful for PHP-CLI. The solution is simple:  echo "\x07"
og at gams dot at
26-Apr-2007 03:06
easy transparent solution for using constants in the heredoc format:
DEFINE('TEST','TEST STRING');

$const = get_defined_constants();

echo <<<END
{$const['TEST']}
END;

Result:
TEST STRING
penda ekoka
24-Apr-2007 08:14
error control operator (@) with heredoc syntax:

the error control operator is pretty handy for supressing minimal errors or omissions. For example an email form that request some basic non mandatory information to your users. Some may complete the form, other may not. Lets say you don't want to tweak PHP for error levels and you just wish to create some basic template that will be emailed to the admin with the user information submitted. You manage to collect the user input in an array called $form:

<?php
// creating your mailer
$mailer = new SomeMailerLib();
$mailer->from = ' System <mail@yourwebsite.com>';
$mailer->to = 'admin@yourwebsite.com';
$mailer->subject = 'New user request';
// you put the error control operator before the heredoc operator to suppress notices and warnings about unset indices like this
$mailer->body = @<<<FORM
Firstname = {$form['firstname']}
Lastname =
{$form['lastname']}
Email =
{$form['email']}
Telephone =
{$form['telephone']}
Address =
{$form['address']}
FORM;

?>
maikel7 at poczta dot onet dot pl
20-Apr-2007 10:45
I was curious about speed differences between "some text $var" and "some text".$var. And my tests seem to be quite the opposite to the benchmarks posted below by "php at moechofe dot com". I used this code:

<?php
function microtime_float() {
   list(
$usec, $sec) = explode(" ", microtime());
   return ((float)
$usec + (float)$sec);
}

$str = "some text";

$time_start = microtime_float();
for (
$i=0; $i<100000; $i++) {
   
$a="x $str o $str a $str d $str f $str";
}
$duration1 = microtime_float() - $time_start;

$time_start = microtime_float();
for (
$i=0; $i<100000; $i++) {
   
$a="x ".$str." o ".$str." a ".$str." d ".$str." f ".$str;
}
$duration2 = microtime_float() - $time_start;
?>

On a windows machine $duration1 is about 2.5x greater (=slower) than $duration2. I ran it also on several hosting servers (Linux-based) and the differnces were smaller but still $duration1 was much greater. Only on one of the hosts where they use eAccellarator there was no difference between the two methods. So my conclusion is not to use "$variables in double-quoted strings" wherever speed is important.
php at moechofe dot com
01-Apr-2007 06:44
A simple benchmark to check differents about :
- simple and double quote concatenation and
- double quote and heredoc replacement

<?php

function test_simple_quote_concat()
{
 
$b = 'string';
 
$a  = ' string'.$b.' string'.$b.' srting'.$b;
 
$a .= ' string'.$b.' string'.$b.' string'.$b;
 
$a .= ' string'.$b.' string'.$b.' string'.$b;
 
$a .= ' string'.$b.' string'.$b.' string'.$b;
 
$a .= ' string'.$b.' string'.$b.' string'.$b;
 
$a .= ' string'.$b.' string'.$b.' string'.$b;
 
$a .= ' string'.$b.' string'.$b.' string'.$b;
 
$a .= ' string'.$b.' string'.$b.' string'.$b;
}

function
test_double_quote_concat()
{
 
$b = "string";
 
$a  = " string".$b." string".$b." string".$b;
 
$a .= " string".$b." string".$b." string".$b;
 
$a .= " string".$b." string".$b." string".$b;
 
$a .= " string".$b." string".$b." string".$b;
 
$a .= " string".$b." string".$b." string".$b;
 
$a .= " string".$b." string".$b." string".$b;
 
$a .= " string".$b." string".$b." string".$b;
 
$a .= " string".$b." string".$b." string".$b;
}

function
test_double_quote_replace()
{
 
$b = "string";
 
$a = " string$b string$b string$b
string
$b string$b string$b
string
$b string$b string$b
string
$b string$b string$b
string
$b string$b string$b
string
$b string$b string$b
string
$b string$b string$b
string
$b string$b string$b";
}

function
test_eot_replace()
{
 
$b = <<<EOT
string
EOT;
 
$a = <<<EOT
string{$b} string{$b} string{$b}
string
{$b} string{$b} string{$b}
string
{$b} string{$b} string{$b}
string
{$b} string{$b} string{$b}
string
{$b} string{$b} string{$b}
string
{$b} string{$b} string{$b}
string
{$b} string{$b} string{$b}
string
{$b} string{$b} string{$b}
EOT;
}

$iter = 2000;

for(
$i=0; $i<$iter; $i++ )
 
test_simple_quote_concat();

for(
$i=0; $i<$iter; $i++ )
 
test_double_quote_concat();

for(
$i=0; $i<$iter; $i++ )
 
test_double_quote_replace();

for(
$i=0; $i<$iter; $i++ )
 
test_eot_replace();

?>

I've use xdebug profiler to obtain the followed results:

test_simple_quote_concat : 173ms
test_double_quote_concat : 161ms
test_double_quote_replace : 147ms
test_eot_replace : 130ms
bryant at zionprogramming dot com
27-Feb-2007 10:16
As of (at least) PHP 5.2, you can no longer convert an object to a string unless it has a __toString method. Converting an object without this method now gives the error:

PHP Catchable fatal error:  Object of class <classname> could not be converted to string in <file> on line <line>

Try this code to get the same results as before:

<?php

if (!is_object($value) || method_exists($value, '__toString')) {
   
$string = (string)$value;
} else {
   
$string = 'Object';
}

?>
fmouse at fmp dot com
21-Feb-2007 08:20
It may be obvious to some, but it's convenient to note that variables _will_ be expanded inside of single quotes if these occur inside of a double-quoted string.  This can be handy in constructing exec calls with complex data to be passed to other programs.  e.g.:

$foo = "green";
echo "the grass is $foo";
the grass is green

echo 'the grass is $foo';
the grass is $foo

echo "the grass is '$foo'";
the grass is 'green'
thomas dot oldbury dot nospam at tgohome dot com
17-Feb-2007 01:33
This function I created to insert a string at a position or an array of positions. Quite useful.

<?php

/*
   
    string    strwpos (string insert, string input, int position [, int mode])
   
    Returns a string with a string inserted at a position,
    or an array of positions. Normally, the string is inserted
    on the right of the position, but it can be inserted on the
    left or both. The following constants define where the string
    should be inserted:
   
        INS_LEFT  -  insert the string left of the position
        INS_RIGHT - insert the string right of the position
        INS_BOTH  -  insert the string on both sides
   
    Returns resulting string on success, FALSE on failure.
   
*/

define('INS_LEFT', 0);
define('INS_RIGHT', 1);
define('INS_BOTH', 2);

function
strwpos($ins, $string, $pos, $mode = INS_RIGHT)
{
   
$str = "";
   
    for(
$c = 0; $c < strlen($string); $c++)
    {
        if(
is_array($pos))
        {
            if(
in_array($c, $pos, true))
            {
                if(
$mode == INS_RIGHT)
                {
                   
$ins_c = substr($string, $c, 1) . $ins;
                }
                elseif(
$mode == INS_LEFT)
                {
                   
$ins_c = $ins . substr($string, $c, 1);
                }
                elseif(
$mode == INS_BOTH)
                {
                   
$ins_c = $ins . substr($string, $c, 1) . $ins;
                }
                else
                {
                   
trigger_error("Unknown mode '$mode' specified", E_USER_WARNING);
                    return
false;
                }
               
$str .= $ins_c;
            }
            else
            {
               
$str .= $string[$c];
            }
        }
        else
        {
            if(
$c == $pos)
            {
                if(
$mode == INS_RIGHT)
                {
                   
$ins_c = substr($string, $c, 1) . $ins;
                }
                elseif(
$mode == INS_LEFT)
                {
                   
$ins_c = $ins . substr($string, $c, 1);
                }
                elseif(
$mode == INS_BOTH)
                {
                   
$ins_c = $ins . substr($string, $c, 1) . $ins;
                }
                else
                {
                   
trigger_error("Unknown mode '$mode' specified", E_USER_WARNING);
                    return
false;
                }
               
$str .= $ins_c;
            }
            else
            {
               
$str .= $string[$c];
            }
        }
    }
   
    return
$str;
}
?>

This function can have a few problems. For example, the following code will produce an unexpected result:

<?php echo strwpos('love, not ', 'I hate you', 2); ?>

It will produce this result:

   I hlove, not ate you

The reason for this is because the string is inserted to the right of the string by default. So using the optional MODE parameter with the INS_LEFT value will produce the result we need.

<?php echo strwpos('love, not ', 'I hate you', 2, INS_LEFT); ?>

This will produce the result we need:

   I love, not hate you

You can also use an array of places to insert the string into:

<?php echo strwpos('brown ', 'The quick fox jumped over the lazy dog', array(10, 35), INS_LEFT); ?>

This will produce the result:

   The quick brown fox jumped over the lazy brown dog

Hope this helps.
bishop
28-Mar-2006 10:58
You may use heredoc syntax to comment out large blocks of code, as follows:
<?php
<<<_EOC
    // end-of-line comment will be masked... so will regular PHP:
    echo (
$test == 'foo' ? 'bar' : 'baz');
    /* c-style comment will be masked, as will other heredocs (not using the same marker) */
    echo <<<EOHTML
This is text you'll never see!       
EOHTML;
    function defintion(
$params) {
        echo 'foo';
    }
    class definition extends nothing     {
       function definition(
$param) {
          echo 'do nothing';
       }      
    }

    how about syntax errors?; = gone, I bet.
_EOC;
?>

Useful for debugging when C-style just won't do.  Also useful if you wish to embed Perl-like Plain Old Documentation; extraction between POD markers is left as an exercise for the reader.

Note there is a performance penalty for this method, as PHP must still parse and variable substitute the string.
adam at obledesign dot com
21-Jan-2006 10:51
If you really want to get constants inside your string you can do something like this (PHP5 only).

<?php

class GetConstant {
 public function
__get($constant_name) {
  return (
defined($constant_name) ? constant($constant_name) : NULL);
 }
}

$C = new GetConstant();

define('FOO','bar');

echo(
"I want a candy {$C->FOO}.");

?>
csaba at alum dot mit dot edu
31-Dec-2005 01:15
Multiline strings:
In most of the strings on this doc page, the heredoc form (<<<) is not needed.  The heredoc form is useful when you also want to embed, without escaping, quotes of the same type as the starting quote.  The single quote form is particularly useful when you want to specify multiline code for future evaluation.

<?php
$code
= '
  $output = "Mutliline output";
  $out = "$output within multiline code:
$ needs escaping within \$out,
and double quotes (\") need escaping within \$out,
but single quotes (\') need escaping everywhere.";
  // Next two lines work with php.exe
  /* on Windows systems */
  $oWSH = new COM("WScript.Shell");
  $oWSH->Popup($out, 4, \'IO Demo\', 131120);
'
;
print
"<pre>$code</pre>";
call_user_func (create_function('', $code));
?>

Happy New Year,
Csaba Gabor from Vienna
webmaster at rephunter dot net
30-Nov-2005 06:57
Use caution when you need white space at the end of a heredoc. Not only is the mandatory final newline before the terminating symbol stripped, but an immediately preceding newline or space character is also stripped.

For example, in the following, the final space character (indicated by \s -- that is, the "\s" is not literally in the text, but is only used to indicate the space character) is stripped:

$string = <<<EOT
this is a string with a terminating space\s
EOT;

In the following, there will only be a single newline at the end of the string, even though two are shown in the text:

$string = <<<EOT
this is a string that must be
followed by a single newline

EOT;
DELETETHIS dot php at dfackrell dot mailshell dot com
01-Nov-2005 06:05
Just some quick observations on variable interpolation:

Because PHP looks for {? to start a complex variable expression in a double-quoted string, you can call object methods, but not class methods or unbound functions.

This works:

<?php
class a {
    function
b() {
        return
"World";
    }
}
$c = new a;
echo
"Hello {$c->b()}.\n"
?>

While this does not:

<?php
function b() {
    return
"World";
}
echo
"Hello {b()}\n";
?>

Also, it appears that you can almost without limitation perform other processing within the argument list, but not outside it.  For example:

<?
$true
= true;
define("HW", "Hello World");
echo
"{$true && HW}";
?>

gives: Parse error: parse error, unexpected T_BOOLEAN_AND, expecting '}' in - on line 3

There may still be some way to kludge the syntax to allow constants and unbound function calls inside a double-quoted string, but it isn't readily apparent to me at the moment, and I'm not sure I'd prefer the workaround over breaking out of the string at this point.
lelon at lelon dot net
27-Oct-2004 09:01
You can use the complex syntax to put the value of both object properties AND object methods inside a string.  For example...
<?php
class Test {
    public
$one = 1;
    public function
two() {
        return
2;
    }
}
$test = new Test();
echo
"foo {$test->one} bar {$test->two()}";
?>
Will output "foo 1 bar 2".

However, you cannot do this for all values in your namespace.  Class constants and static properties/methods will not work because the complex syntax looks for the '$'.
<?php
class Test {
    const
ONE = 1;
}
echo
"foo {Test::ONE} bar";
?>
This will output "foo {Test::one} bar".  Constants and static properties require you to break up the string.
Jonathan Lozinski
06-Aug-2004 10:03
A note on the heredoc stuff.

If you're editing with VI/VIM and possible other syntax highlighting editors, then using certain words is the way forward.  if you use <<<HTML for example, then the text will be hightlighted for HTML!!

I just found this out and used sed to alter all EOF to HTML.

JAVASCRIPT also works, and possibly others.  The only thing about <<<JAVASCRIPT is that you can't add the <script> tags..,  so use HTML instead, which will correctly highlight all JavaScript too..

You can also use EOHTML, EOSQL, and EOJAVASCRIPT.
www.feisar.de
28-Apr-2004 05:49
watch out when comparing strings that are numbers. this example:

<?php

$x1
= '111111111111111111';
$x2 = '111111111111111112';

echo (
$x1 == $x2) ? "true\n" : "false\n";

?>

will output "true", although the strings are different. With large integer-strings, it seems that PHP compares only the integer values, not the strings. Even strval() will not work here.

To be on the safe side, use:

$x1 === $x2
atnak at chejz dot com
12-Apr-2004 01:53
Here is a possible gotcha related to oddness involved with accessing strings by character past the end of the string:

$string = 'a';

var_dump($string[2]);  // string(0) ""
var_dump($string[7]);  // string(0) ""
$string[7] === '';  // TRUE

It appears that anything past the end of the string gives an empty string..  However, when E_NOTICE is on, the above examples will throw the message:

Notice:  Uninitialized string offset:  N in FILE on line LINE

This message cannot be specifically masked with @$string[7], as is possible when $string itself is unset.

isset($string[7]);  // FALSE
$string[7] === NULL;  // FALSE

Even though it seems like a not-NULL value of type string, it is still considered unset.
dandrake
20-Jan-2004 01:41
By the way, the example with the "\n" sequence will insert a new line in the html code, while the output will be decided by the HTML syntax. That's why, if you use

<?
 
echo "Hello \n World";
?>

the browser will receive the HTML code on 2 lines
but his output on the page will be shown on one line only.
To diplay on 2 lines simply use:

<?
 
echo "Hello <br>World";
?>

like in HTML.
philip at cornado dot com
12-Apr-2003 03:37
Note that in PHP versions 4.3.0 and 4.3.1, the following provides a bogus E_NOTICE (this is a known bug):

echo "$somearray['bar']";

This is accessing an array inside a string using a quoted key and no {braces}.  Reading the documention shows all the correct ways to do this but the above will output nothing on most systems (most have E_NOTICE off) so users may be confused.  In PHP 4.3.2, the above will again yield a parse error.
03-Mar-2003 08:04
Regarding "String access by character":

Apparently if you edit a specific character in a string, causing the string to be non-continuous, blank spaces will be added in the empty spots.

echo '<pre>';
$str = '0123';
echo "$str\n";
$str[4] = '4';
echo "$str\n";
$str[6] = '6';
echo "$str\n";

This will output:
0123
01234
01234 6
Notice the blank space where 5 should be.
vallo at cs dot helsinki dot fi
04-Nov-2002 03:41
Even if the correct way to handle variables is determined from the context, some things just doesn't work without doing some preparation.

I spent several hours figuring out why I couldn't index a character out of a string after doing some math with it just before. The reason was that PHP thought the string was an integer!

$reference = $base + $userid;
.. looping commands ..
$chartohandle = $reference{$last_char - $i};

Above doesn't work. Reason: last operation with $reference is to store a product of an addition -> integer variable. $reference .=""; (string catenation) had to be added before I got it to work:

$reference = $base + $userid;
$reference .= "";
.. looping commands ..
$chartohandle = $reference{$last_char - $i};

Et voilá! Nice stream of single characters.
guidod at gmx dot de
23-Jul-2002 09:26
PHP's double-quoted strings are inherently ill-featured - they will be a problem especially with computed code like in /e-evals with preg_replace.

bash and perl follow the widely accepted rule that all backslashes will escape the nextfollowing char, and nonalpha-chars will always get printed there as themselves whereas (the unescaped chars might have special meaning in regex). Anyway, it is a great way to just escape all nonalpha chars that you uncertain about whether they have special meaning in some places, and ye'll be sure they will get printed literal.

Furthermore, note that \{ sequence is not mentioned in the  escape-char table! You'll get to know about it only "complex (curly) syntax". This can even more be a problem with evals, as they behave rather flaky like it _cannot_ be accomodated for computed code. Try all variants of `echo "hello \{\$world}"` removing one or more of the chars in the \{\$ part - have fun!
philip at cornado dot com
10-Aug-2000 11:38
A nice "Introduction to PHP Strings" tutorial:
  http://www.zend.com/zend/tut/using-strings.php

Matrices> <Números de punto flotante
Last updated: Tue, 27 Nov 2007
 
 
show source | credits | sitemap | contact | advertising | mirror sites