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

search for in the

Масиви> <Числа с плаваща запетая
Last updated: Fri, 27 Jun 2008

view this page in

Низове

Низът представлява поредица от знаци. В PHP, знакът е същото като байт, т.е., съществуват точно 256 възможни знака. Това също означава, че PHP няма естествена поддръжка за Unicode. Вж. utf8_encode() и utf8_decode() за Unicode поддръжка.

Забележка: За даден низ не е проблем да стане много дълъг. Няма практическо ограничение в размера на низовете, наложено от PHP, така че не трябва да се безпокоите за дългите низове.

Синтаксис

Низов литерал може да бъде дефиниран по три различни начина.

Поставяне в апострофи

Най-лесният начин да се дефинира обикновен низ е да се загради с апострофи (знакът ').

За да укажете знака апостроф, трябва да го екранирате с обратно-наклонена черта (\), както това се прави и в редица други езици. Ако все пак се налага преди апострофа да се появи обратно-наклонена черта, ще трябва да я дублирате. Отбележете, че ако се опитате да екранирате който и да е друг знак, обратно-наклонената черта също ще бъде отпечатана! Така че обикновено тя няма нужда да бъде екранирана.

Забележка: В PHP 3 ще бъде изведено предупреждение от ниво E_NOTICE, когато това се случи.

Забележка: За разлика от другите два синтаксиса, тук променливите и екраниращите последователности за специални знаци няма да бъдат обработени.

<?php
echo 'това е обикновен низ';

echo 
'Можете също да поставяте и
нови редове по този
начин'
;

// Извежда: Арнолд веднъж каза: "I'll be back"
echo 'Арнолд веднъж каза: "I\'ll be back"';

// Извежда: Вие изтрихте C:\*.*?
echo 'Вие изтрихте C:\\*.*?';

// Извежда: Вие изтрихте C:\*.*?
echo 'Вие изтрихте C:\*.*?';

// Извежда: Това няма да се изведе: \n - нов ред
echo 'Това няма да се изведе: \n - нов ред';

// Извежда: Променливите също: $alpha $beta
echo 'Променливите също: $alpha $beta';
?>

Поставяне в кавички

Ако низът е заграден в кавички ("), PHP разбира повече екраниращи последователности за специални знаци:

Екранирани знаци
последователност значение
\n нов ред (LF или 0x0A (10) в ASCII)
\r връщане на каретката (CR или 0x0D (13) в ASCII)
\t табулация (HT или 0x09 (9) в ASCII)
\v вертикална табулация (VT или 0x0B (11) в ASCII) (от PHP 5.2.5)
\f form feed (FF или 0x0C (12) в ASCII) (от PHP 5.2.5)
\\ обратно-наклонена черта
\$ знак за долар
\" кавичка
\[0-7]{1,3} последователността от знаци, съвпадаща с регулярния израз, е знак в осмична бройна система
\x[0-9A-Fa-f]{1,2} последователността от знаци, съвпадаща с регулярния израз, е знак в шестнайсетична бройна система

И тук ако се опитате да екранирате който и да е друг знак, обратно-наклонената черта също ще бъде отпечатана! Преди PHP 5.1.1, обратно-наклонената черта в \{$var} не се отпечатваше.

Най-важната особеност на кавичките, обаче, е че променливите ще бъдат обработени. За повече информация вижте разбор на низ.

Heredoc

Друг начин да се дефинира низ е да се използва синтаксис от тип heredoc ("<<<"). След <<< трябва да се укаже идентификатор (последван от нов ред), след това низа и накрая самия идентификатор, който да затвори цитата.

Затварящият идентификатор трябва да започне в първата колона на реда. Освен това, използваният идентификатор трябва да следва същите правила за именуване като всеки друг етикет в PHP: трябва да се състои единствено от буквено-цифрови знаци или подчертавки и трябва да започва със знак, който не е цифра.

Предупреждение

Много важно е да се отбележи, че на реда със затварящия идентификатор няма никакви други знаци, освен по възможност точка и запетая (;). Това преди всичко означава, че идентификаторът не може да бъде отместван като абзац и не може да има никакви интервали или табулации преди или след точката и запетаята. Важно е също да се разбере, че първият знак преди затварящия идентификатор трябва да бъде знака за нов ред, както е дефиниран от съответната операционна система. Например на Macintosh това е \r. Освен това, затварящият идентификатор (по желание последван от точка и запетая) трябва да бъде последван и от знак за нов ред.

Ако това правило не се спази и затварящият идентификатор не е "чист", тогава той няма да бъде възприет като такъв и PHP ще продължи да го търси. Ако в този случай не бъде намерен правилен затварящ идентификатор, това ще доведе до синтактична грешка с номер на реда в края на скрипта.

Не е разрешена употребата на синтаксис от тип heredoc в инициализиране на членове на клас. В този случай използвайте другите низови синтаксиси.

Example #1 Невалиден пример

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

Heredoc текстът работи по същия начин както и низът в кавички, само че без кавичките. Това означава, че няма нужда да екранирате кавичките, но че можете да използвате екраниращите кодове изброени по-горе. Променливите биват обработени, но трябва да се внимава при изразяване на сложни променливи вътре в heredoc, какъвто е и случаят с низовете.

Example #2 Пример за цитат от тип heredoc

<?php
$str 
= <<<EOD
Пример за низ,
който преминава на няколко
реда със синтаксис heredoc.
EOD;

/* По-сложен пример, с променливи. */
class foo
{
    var 
$foo;
    var 
$bar;

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

$foo = new foo();
$name 'MyName';

echo <<<EOT
Казвам се "$name". Отпечатвам някое $foo->foo.
Сега, отпечатвам накое 
{$foo->bar[1]}.
Това трябва да отпечата главно 'A': \x41
EOT;
?>

Забележка: Поддръжката на heredoc беше добавена в PHP 4.

Анализиране на променливи

Когато даден низ се дефинира в кавички или с heredoc, променливите в него биват анализирани.

Съществуват два типа синтаксис: прост и сложен. Простият синтаксис е най-разпространен и удобен. Той предлага начин да се анализира променлива, стойност от масив, или свойство на обект.

Сложният синтаксис беше въведен в PHP 4 и може да бъде разпознат по фигурните скоби, заграждащи израза.

Прост синтаксис

Ако срещне знака за долар ($), синтактичният анализатор ще се опита да поеме лакомо колкото се може повече знаци, за да образува валидно име на променлива. Заградете името на променливата във фигурни скоби, ако искате изрично да укажете края на името.

<?php
$beer 
'Kamenitza';
echo 
"$beer's taste is great"// работи, "'" е невалиден знак за име на променлива
echo "He drank some $beers";   // няма да работи, 's' е валиден знак за име на променлива
echo "He drank some ${beer}s"// работи
echo "He drank some {$beer}s"// работи
?>

По същия начин се прави разбор и на елемент от масив или свойство на обект. При индексите на масиви, затварящата квадратна скоба (]) обозначава края на индекса. За свойствата на обекти важат същите правила както за обикновените променливи, макар че при обектните свойства не съществува трик като този при променливите.

<?php
// Тези примери са специфични за употребата на масиви в низове.
// Извън низ, винаги заграждайте с апострофи низовите ключове на масиви
// и съответно - не използвайте {фигурни скоби}.

// Нека се показват всички грешки
error_reporting(E_ALL);

$fruits = array('strawberry' => 'red''banana' => 'yellow');

// Работи, но отбележете, че това работи по друг начин извън низовите кавички
echo "A banana is $fruits[banana].";

// Работи
echo "A banana is {$fruits['banana']}.";

// Работи, но PHP първо търси константа с името "banana",
// както е обяснено по-долу.
echo "A banana is {$fruits[banana]}.";

// Няма да работи, използвайте фигурни скоби. Това ще предизвика синтактична грешка.
echo "A banana is $fruits['banana'].";

// Работи
echo "A banana is " $fruits['banana'] . ".";

// Работи
echo "This square is $square->width meters broad.";

// Няма да работи. За решение, вижте сложния синтаксис.
echo "This square is $square->width00 centimeters broad.";
?>

За всичко по-сложно трябва да използвате сложния синтаксис.

Сложен (фигурен) синтаксис

Името "сложен" не е защото синтаксисът е сложен, а защото чрез него можете да включвате сложни изрази.

На практика, с този синтаксис можете да включите в низ коя да е стойност, която е налична в пространството от имена. Просто пишете израза по същия начин както бихте го направили извън низа, след което го поставете между { и }. Тъй като не можете да екранирате '{', този синтаксис ще бъде разпознат единствено, когато $ следва непосредствено {. (Използвайте "{\$", за да получите литерала "{$"). Няколко разяснителни примера:

<?php
// Нека се показват всички грешки
error_reporting(E_ALL);

$great 'fantastic';

// Няма да работи, извежда: This is { fantastic}
echo "This is { $great}";

// Работи, извежда: This is fantastic
echo "This is {$great}";
echo 
"This is ${great}";

// Работи
echo "This square is {$square->width}00 centimeters broad."

// Работи
echo "This works: {$arr[4][3]}";

// Това е грешно по същата причина, поради която и $foo[bar] е грешно
// извън низ. С други думи, ще работи, но понеже PHP първо
// ще потърси константата foo, ще хвърли грешка от ниво
// E_NOTICE (недефинирана константа).
echo "This is wrong: {$arr[foo][3]}"

// Работи. При многомерни масиви, винаги поставяйте
// фигурни скоби около масивите, когато са в низове.
echo "This works: {$arr['foo'][3]}";

// Работи.
echo "This works: " $arr['foo'][3];

echo 
"You can even write {$obj->values[3]->name}";

echo 
"This is the value of the var named $name: {${$name}}";

echo 
"This is the value of the var named by the return value of getName(): {${getName()}}";

echo 
"This is the value of the var named by the return value of \$object->getName(): {${$object->getName()}}";
?>

Забележка: Извикването на функции и методи в рамките на {$ } работи от PHP 5.

Забележка: Разборът на променливи в рамките на низове използва повече памет отколкото свързването на низове. Когато пишете PHP скрипт, в който паметта е фактор, обмислете възможността да използвате оператора за свързване (.), а не разбор на променливи.

Познаков достъп и изменение в низ

Знаците в даден низ могат да бъдат достъпвани и изменяни чрез указване на отместване от нулата за желания знак след низа посредством квадратни скоби, например $str[42], така че бихте могли да мислите за даден низ като за масив от знаци.

Забележка: Те също могат да бъдат достъпвани и с фигурни скоби - $str{42}, със същата цел. Все пак, употребата на квадратни скоби е за предпочитане, тъй като {фигурният} стил става непрепоръчителен от PHP 6.

Example #3 Някои низови примери

<?php
// Вземане на първия знак от низ.
$str 'Това е тест.';
$first $str[0];

// Вземане на третия знак от низ.
$third $str[2];

// Вземане на последния знак от низ.
$str 'Това продължава да бъде тест.';
$last $str[strlen($str)-1];

// Промяна на последния знак от низ.
$str 'На масата има ябълка';
$str[strlen($str)-1] = 'и';

// Алтернативният метод с {} е непрепоръчителен от PHP 6
$third $str{2};
?>

Забележка: Достъпването до променливи от друг тип с [] или {} мълчаливо връща NULL.

Полезни функции и оператори

Низовете могат да бъдат съединявани посредством оператора '.' (точка). Забележете, че операторът '+' (събиране) няма да направи това. За повече информация вижте Низови оператори.

Съществуват доста на брой полезни функции за изменение на низове.

За основните функции вижте раздел низови функции, а за по-сложно търсене и заместване - функциите за регулярни изрази (в две разновидности: Perl и POSIX разширения).

Има също функции за URL низове и функции за криптиране и декриптиране на низове (mcrypt и mhash).

Накрая, ако все още не сте намерили това, което търсите, вижте също и функциите за типове знаци.

Преобразуване в низ

Можете да превърнете стойност в низ посредством преобразуването (string) или функцията strval(). Низовото преобразуване се извършва автоматично в обхвата на израз, който се нуждае от низ. Това се случва, когато използвате функциите echo() и print(), или когато сравнявате стойността на променлива с низ. Прочитането на разделите за Типове и Манипулации с типове ще направи нещата още по-ясни. Вж. също settype().

Булевата стойност TRUE се преобразува в низа "1", а стойността FALSE се представя като "" (празен низ). По този начин можете да преобразувате двупосочно между булеви и низови стойности.

Цяло число (integer) или число с плаваща запетая (float) се преобразува в низ, който се състои от цифрите на числото (включително и експонентата - за числата с плаваща запетая). Числата с плаваща запетая може да бъдат преобразувани посредством експоненциалната система за означаване (4.1E+6).

Забележка: Знакът за десетична запетая се дефинира в локалните настройки на скрипта (категория LC_NUMERIC). Вж. setlocale().

Масивите винаги се преобразуват в низа "Array", така че не можете да покажете съдържанието на даден масив с echo() или print(). За да видите един елемент, трябва да направите нещо от рода на echo $arr['foo']. Погледнете по-долу за начини за показване на цялото съдържание.

Обектите в PHP 4 винаги се преобразуват в низа "Object". Ако искате да покажете стойностите на член-променливите на даден обект, с цел отстраняване на програмни грешки, прочетете следващите абзаци. За да видите името на класа, на който е инстанция обектът, използвайте get_class(). От PHP 5 се използва метода __toString(), ако е приложим.

Ресурсите винаги се преобразуват в низове със структура "Resource id #1", където 1 е уникалното число на ресурса, присвоено от PHP по време на изпълнение. Ако искате да вземете типа на ресурса, използвайте get_resource_type().

NULL винаги се преобразува в празен низ.

Както можете да видите по-горе, отпечатването на масиви, обекти или ресурси не ви предоставя никаква полезна информация за самите стойности. Разгледайте функциите print_r() и var_dump() за по-добри начини за показване на стойностите, в процеса на отстраняване на грешки.

Можете също да превърнете стойности от PHP в низове за постоянно съхранение. Този метод се нарича сериализация и може да се осъществи посредством функцията serialize(). Можете също да сериализирате стойности от PHP в XML структури, стига във вашата инсталация на PHP да имате поддръжка за WDDX.

Превръщане на низ в число

Когато даден низ бъде разпознат като число, резултантната стойност и типът се определят както следва.

Низът ще се изчисли като плаващо ако съдържа който и да е от знаците '.', 'e' или 'E'. В противен случай, ще се изчисли като цяло число.

Стойността се взима от първата част на низа. Ако низът започва с валидни числови данни, това ще бъде и използваната стойност. В противен случай стойността ще бъде 0 (нула). Валидните числови данни са незадължителен знак, последван от една или повече цифри (по желание съдържащи и плаваща запетая), последвани от незадължителна експонента. Експонентата се изразява с латинската буква 'e' или 'E', последвана от една или повече цифри.

<?php
$foo 
"10.5";                // $foo е плаващо (11.5)
$foo "-1.3e3";              // $foo е плаващо (-1299)
$foo "bob-1.3e3";           // $foo е цяло число (1)
$foo "bob3";                // $foo е цяло число (1)
$foo "10 малки прасета";    // $foo е цяло число (11)
$foo "10.2 малки прасенца"// $foo е плаващо (14.2)
$foo "10.0 прасета " 1;       // $foo е плаващо (11)
$foo "10.0 прасета " 1.0;     // $foo е плаващо (11)     
?>

За повече информация относно това преобразуване вижте страницата от ръководството на Unix за strtod(3).

В случай, че искате да проверите някой от примерите в този раздел, можете да ги препишете и да сложите следния ред, за да се уверите сами какво се случва:

<?php
echo "\$foo==$foo; типът е " gettype ($foo) . "<br />\n";
?>

Не разчитайте да получите кода на даден низ като го преобразувате в цяло число (както бихте направили в C например). Използвайте функциите ord() и chr(), за да правите преобразувания между знаци и съответните им кодове.



Масиви> <Числа с плаваща запетая
Last updated: Fri, 27 Jun 2008
 
add a note add a note User Contributed Notes
Низове
steve at mrclay dot org
30-Sep-2008 10:33
Simple function to create human-readably escaped double-quoted strings for use in source code or when debugging strings with newlines/tabs/etc.

<?php
function doubleQuote($str) {
   
$ret = '"';
    for (
$i = 0, $l = strlen($str); $i < $l; ++$i) {
       
$o = ord($str[$i]);
        if (
$o < 31 || $o > 126) {
            switch (
$o) {
                case
9: $ret .= '\t'; break;
                case
10: $ret .= '\n'; break;
                case
11: $ret .= '\v'; break;
                case
12: $ret .= '\f'; break;
                case
13: $ret .= '\r'; break;
                default:
$ret .= '\x' . str_pad(dechex($o), 2, '0', STR_PAD_LEFT);
            }
        } else {
            switch (
$o) {
                case
36: $ret .= '\$'; break;
                case
34: $ret .= '\"'; break;
                case
92: $ret .= '\\\\'; break;
                default:
$ret .= $str[$i];
            }
        }
    }
    return
$ret . '"';
}
?>
chAlx at findme dot if dot u dot need
11-Sep-2008 05:42
To save Your mind don't read previous comments about dates  ;)

When both strings can be converted to the numerics (in ("$a" > "$b") test) then resulted numerics are used, else FULL strings are compared char-by-char:

<?php
var_dump
('1.22' > '01.23'); // bool(false)
var_dump('1.22.00' > '01.23.00'); // bool(true)
var_dump('1-22-00' > '01-23-00'); // bool(true)
var_dump((float)'1.22.00' > (float)'01.23.00'); // bool(false)
?>
harmor
02-Sep-2008 12:05
So you want to get the last character of a string using "String access and modification by character"?  Well negative indexes are not allowed so $str[-1] will return an empty string.

<?php
//Tested using: PHP 5.2.5

$str = 'This is a test.';

$last = $str[-1];                  //string(0) ""
$realLast = $str[strlen($str)-1];  //string(1) "."
$substr = substr($str,-1);         //string(1) "."

echo '<pre>';
var_dump($last);
var_dump($realLast);
var_dump($substr);
nullhility at gmail dot com
06-Jun-2008 09:40
It's also valuable to note the following:

<?php
${date("M")} = "Worked";
echo ${
date("M")};
?>

This is perfectly legal, anything inside the braces is executed first, the return value then becomes the variable name. Echoing the same variable variable using the function that created it results in the same return and therefore the same variable name is used in the echo statement. Have fun ;).
sk89q
30-Apr-2008 09:46
<?php
$F
= "F";
function
F($s) { return $s; }
$filename = '<some code>';
echo
"{$F(htmlspecialchars($filename))}";
?>
yuku
01-Apr-2008 04:21
This example of the heredoc has wrong output:
Code: This should print a capital 'A': \x41
Output should be: This should print a capital 'A': A

The example of the nowdoc has wrong code:
Code: This should not print a capital 'A': x41
That should be: This should not print a capital 'A': \x41
chris at chrisstockton dot org
24-Mar-2008 03:58
For anyone who reads Evan K, please note that:
// a string to test, and show the before and after
$before = 'Quantity:\t500\nPrice:\t$5.25 each';
$after = expand_escape($before);
var_dump($before, $after);

Is identical to (note all I added was a backslash before $):
$before = "Quantity:\t500\nPrice:\t\$5.25 each";
var_dump($before);

So its definitely better to escape a dollar instead of all the overhead of his regex and evals and such, although clever completely unnecessary.

-Chris
Evan K
28-Feb-2008 10:03
I encountered the odd situation of having a string containing unexpanded escape sequences that I wanted to expand, but also contained dollar signs that would be interpolated as variables.  "$5.25\n", for example, where I want to convert \n to a newline, but don't want attempted interpolation of $5.

Some muddling through docs and many obscenties later, I produced the following, which expands escape sequences in an existing string with NO interpolation.

<?php

// where we do all our magic
function expand_escape($string) {
    return
preg_replace_callback(
       
'/\\\([nrtvf]|[0-7]{1,3}|[0-9A-Fa-f]{1,2})?/',
       
create_function(
           
'$matches',
           
'return ($matches[0] == "\\\\") ? "" : eval( sprintf(\'return "%s";\', $matches[0]) );'
       
),
       
$string
   
);
}

// a string to test, and show the before and after
$before = 'Quantity:\t500\nPrice:\t$5.25 each';
$after = expand_escape($before);
var_dump($before, $after);

/* Outputs:
string(34) "Quantity:\t500\nPrice:\t$5.25 each"
string(31) "Quantity:    500
Price:    $5.25 each"
*/

?>
dot dot dot dot dot alexander at gmail dot com
07-Feb-2008 07:31
I think there's not that much to string comparison as claiming date recognition:

It's simply comparing ordinal values of the characters from the {0} to the {strlen-1} one.
In this case
<?php
$a
= '2007-11-06 15:17:48';
$b = '2007-11-05 15:17:48';

var_dump($a > $b);
?>
mArIo@luigi ~ $: php test.php
bool(true)
here all characters match till it reaches position 9 (the "day")
there, 6 has a bigger ord()inal value than 5

<?php
$a
= 'January 25th, 2008 00:23:38';
$b = 'Janury 24th, 2008 00:23:37'; // ($a > $b) === false
?>
Here when we reach 'r' in "Janury" we see that "a" is "less" than "r" so the example would evaluate as ($a < $b) === true

Here:
<?php
$a
= 'February 1st, 2008 00:23:38';
$b = 'January 25th, 2008 00:23:38';
?>
as expected the letter "F" comes before "J" as an ordinal character, so $a is less than $b
 Even here:
<?php
var_dump
('Z' > 'M'); //bool(true)
?>
it gets confirmed that the string comparison operators >, <, =>, =<, == just do a ordinal character comparison starting from position {0} to the first difference or the end of the string.
topnotcher at mail dot uri dot edu
28-Jan-2008 05:25
@qriz at example dot com

Numerical comparisons, such as <, > are simply _NOT_ valid on strings.  Thus, before a comparison can be made by a numerical comparison operator, the operands must be _casted_ to a numerical type (either float or int).  What I was attempting to say in my previous post is that >, < are date-aware; the tests I included were examples, and not intended to represent the full scope of my comparison.

"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."

What you say here is mere assumption; a few quick tests show that this is indeed not the case.  If PHP indeed compares only the last character in the string, then the following assertion should be false:

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

var_dump($a > $b);
?>
mArIo@luigi ~ $: php test.php
bool(true)

Further, consider the following choices for $a and $b, which, as expected, demonstrate that the <, > operators can indeed understand date formats:

<?php
$a
= 'January 25th, 2008 00:23:37';
$b = 'January 24th, 2008 00:23:38'; // ($a > $b) === true, but 8
?>

If you remain unconvinced, consider what happens if I spell January incorrectly:

<?php
$a
= 'January 25th, 2008 00:23:38';
$b = 'Janury 24th, 2008 00:23:37'; // ($a > $b) === false
?>

Looks like it can understand ISO 8601 date formats? (for more information, see http://en.wikipedia.org/wiki/ISO_8601)

Further investigation yields that this doesn't even work as it should:
<?php
$a
= 'February 1st, 2008 00:23:38';
$b = 'January 25th, 2008 00:23:38';

var_dump($a > $b); //bool(false)

var_dump(strtotime($a)); //int(1201843418)
var_dump(strtotime($b)); //int(1201238618)
var_dump(strtotime($a) - strtotime($b)); //int(604800)
?>
Keeping $b constant and varying the month in $a shows that this comparison correctly interprets the date with the following months: January,March,May,June,July,September,October,November.  Interestingly enough, these are all the months having the property that ord($a[0]) >= ord($b[0]).

<?php
var_dump
('Z' > 'M'); //bool(true)
?>

Conclusion:
The <,> comparison operators definitely have functionality that is undocumented, including date awareness; however, this functionality may not always work as expected and should not be trusted for portability.
yuchunjiang at gmail dot com
23-Jan-2008 03:38
this is the sql string that use the variable and and \' and function.It generate the correct result.
 
$sql1=<<<EOT
INSERT INTO hp_visitHistory ( col1,col2,col3)
VALUES ( NOW(), '{$col2}', '{$_SERVER['REQUEST_URI']}')
EOT;
echo $sql1;
qriz at example dot com
13-Nov-2007 06: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 01: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...
 */
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 09: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
03-Jul-2007 11: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";
Richard Neill
01-Jun-2007 05: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 02: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 07: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;

?>
php at moechofe dot com
01-Apr-2007 05: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 09: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 07: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'
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.
webmaster at rephunter dot net
30-Nov-2005 05: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 05: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 09: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 04: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 12: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 12: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 02: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 07: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 02: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 08: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!