curly brackets for strings
<?php
$test_array = array("hey","people");
$key = 0;
$key1 = 1;
$letter = 0;
echo($test_array[$key]{$letter});
echo($test_array[$key1]{$letter});
?>
result: "hp"
string
Bir dizge string türünde bir sayıl değer olup bir dizi karakterden oluşur. Bu bakımdan her karakter tek bayt ile ifade edilir. Yani, olası karakter sayısı 256'dan ibarettir. Bu yüzden PHP Evrenkod için yerleşik desteğe sahip olamıyor. Temel Evrenkod işlevselliği hakkında bilgi edinmek için utf8_encode() ve utf8_decode() işlevlerine bakınız.
Bilginize: Bir dizgenin çok büyük olması bir sorun teşkil etmez. PHP, string türünde bir değer için boyut sınırlaması yapmaz; tek sınırlama PHP'nin çalıştığı makinede PHP'nin kullanımına ayrılan bellek miktarıdır.
Sözdizimi
string türünde bir sayıl dört şekilde belirtilebilir:
- tek tırnaklı dizge
- çift tırnaklı dizge
- yorumlu metin (heredoc)
- yorumsuz metin (nowdoc) - (PHP 5.3.0 ve sonrası)
Tek tırnaklı dizgeler
Bir dizgeyi belirtmenin en basit yolu dizgeyi tek tırnak (') imlerinin arasına almaktır.
Tek tırnaklı bir dizge içinde tek tırnağı sayıl değeriyle kullanmak isterseniz önüne bir tersbölü imi getirmelisiniz (\). Bir tersbölü imini sayıl değeriyle kullanmak isterseniz onun da önüne bir tersbölü imi getirmelisiniz (\\). Tersbölü imini bunlardan başka bir karakterin önünde kullanırsanız, tersbölü imi karakterle birlikte basılır.
Bilginize: Diğer üç sözdiziminin aksine, değişkenler ve özel karakterlerin öncelemleri tek tırnaklı dizgelerin içinde kullanıldıklarında yorumlanmazlar.
<?php
echo 'Bu basit bir dizgedir';
echo 'Dizgelerin içinde satırsonu karakterlerini
tıpkı buradaki gibi
kullanabilirsiniz';
// Çıktısı: Arnold dedi ki: "I'll be back"
echo 'Arnold dedi ki: "I\'ll be back"';
// Çıktısı: You deleted C:\*.*?
echo 'You deleted C:\\*.*?';
// Çıktısı: You deleted C:\*.*?
echo 'You deleted C:\*.*?';
// Çıktısı: This will not expand: \n a newline
echo 'This will not expand: \n a newline';
// Çıktısı: Variables do not $expand $either
echo 'Variables do not $expand $either';
?>
Çift tırnaklı dizgeler
Eğer bir dizge çift tırnak (") içine alınmışsa PHP, aşağıdaki özel karakter öncelemlerini yorumlayacaktır:
| Öncelem | Anlamı |
|---|---|
| \n | satırsonu (LF veya ASCII 10 (0x0A)) |
| \r | satırbaşı (CR veya ASCII 13 (0x0D)) |
| \t | yatay sekme (HT veya ASCII 9 (0x09)) |
| \v | düşey sekme (VT veya ASCII 11 (0x0B)) (PHP 5.2.5 ve sonrası) |
| \f | sayfa ileri (FF veya ASCII 12 (0x0C)) (PHP 5.2.5 ve sonrası) |
| \\ | tersbölü |
| \$ | dolar imi |
| \" | çift tırnak |
| \[0-7]{1,3} | Bu düzenli ifade ile eşleşen dizilim, karakterin sekizlik gösterimidir. |
| \x[0-9A-Fa-f]{1,2} | Bu düzenli ifade ile eşleşen dizilim, karakterin onaltılık gösterimidir. |
Tersbölü imini bunlardan başka bir karakterin önünde kullanırsanız, tersbölü imi karakterle birlikte basılır. PHP 5.1.1'den önce, \{$var} içindeki tersbölü imi basılmıyordu.
Çift tırnaklı dizgelerin en önemli özelliği içerdiği değişkenlerin yorumlanmasıdır. Bu konuda daha ayrıntılı bilgi edinmek için Değişken çözümleme bölümüne bakınız.
Yorumlu metinler
Bir dizgenin sınırlarını belirlemenin üçüncü yolu, yorumlu metin sözdizimidir. Bir yorumlu metin daima <<< karakterleri ile başlar ve hemen ardından bir betimleyici ve bir satırsonu karakteri gelir. Asıl dizge satırsonu karakterinden sonra yer alır. Dizgenin sonunu belirtmek üzere dizgenin sonuna, baştaki betimleyici konur.
Kapanış betimleyicisinin dizgeden sonraki satırın başında olması gerekir. Ayrıca, betimleyici PHP'deki diğer isimlere uygulanan kurallara uygun olmalıdır: Sadece bir harfle veya alt çizgi imi ile başlayabilir; sadece harfler, rakamlar veya alt çizgi imleri içerebilir.
Kapanış betimleyicisinin bulunduğu satırda betimleyicinin hemen ardına konan noktalı virgül (;) dışında hiçbir karakter bulunmaması çok önemli olup buna özellikle dikkat etmelisiniz. Yani, betimleyici özellikle girintilenmemeli; noktalı virgülden önce ve sonra herhangi bir boşluk karakteri bulunmamalıdır. Ayrıca, kapanış betimleyicisinden hemen önce gelen karakterin yerel işletim sistemine özgü satırsonu karakteri olması çok önemlidir. Bu karakter Unix ve Mac OS X için \n'dir. Kapanış betimleyicisinden (ve olası noktalı virgül karakterinden) sonraki karakter de böyle bir satırsonu karakteri olmalıdır.
Eğer bu kurallara uyulmaz ve kapanış betimleyicisinin etrafı temiz tutulmazsa kapanış betimleyicisi algılanamayacağından PHP kapanış betimleyicisini aramaya devam edecektir. Eğer dosyanın sonuna kadar uygun bir kapanış betimleyicisi bulunamazsa son satırda bir çözümleme hatası oluşacaktır.
Yorumlu metinler sınıf özelliklerini ilklendirmek için kullanılamazlar. PHP 5.3'ten beri bu sınırlama sadece değişken içeren yorumlu metinler için geçerlidir. Bunun yerine yorumsuz metinler kullanılabilir.
Örnek 1 - Geçersiz örnek
<?php
class foo {
public $bar = <<<EOT
bar
EOT;
}
?>
Yorumlu metinler tıpkı çift tırnaklı dizgeler gibi davranırlar. Yorumlu metin çift tırnaklar arasına alınmaz ve metin içindeki çift tırnak imlerinin tersbölü ile öncelenmesi gerekmez, ancak yukarıda çift tırnaklı dizgeler için belirtilen öncelem kodları kullanılabilir. Değişkenler yorumlanır, fakat yorumlanan metin içinde yer alan karmaşık değişkenler ifade edilirken dizgelerde dikkate alınması gerekenler yorumlu metinlerde de dikkate alınmalıdır.
Örnek 2 - Yorumlu metin örneği
<?php
$str = <<<EOD
Yorumlu metin sözdizimi
kullanılarak çok sayıda
satıra bölünmüş dizge örneği.
EOD;
/* Değişkenlerin de kullanıldığı daha karmaşık bir örnek */
class foo
{
var $foo;
var $bar;
function foo()
{
$this->foo = 'Foo';
$this->bar = array('Bar1', 'Bar2', 'Bar3');
}
}
$foo = new foo();
$name = 'Kimimben';
echo <<<EOT
Adım "$name" ve işim $foo->foo basmak.
Şimdi {$foo->bar[1]} basıyorum.
Bu büyük 'A' basmalı: \x41\n
EOT;
?>
Yukarıdaki örneğin çıktısı:
Adım "Kimimben" ve işim Foo basmak. Şimdi Bar2 basıyorum. Bu büyük 'A' basmalı: A
Ayrıca işlev değiştirgesinde veri aktarırken de yorumlu metin kullanılabilir:
Örnek 3 - Değiştirgelerde yorumlu metin kullanımı
<?php
var_dump(array(<<<EOD
foobar!
EOD
));
?>
PHP 5.3.0'dan itibaren, duruk değişkenleri ve sınıf özelliklerini veya sabitlerini yorumlu metin sözdizimini kullanarak ilklendirmek mümkündür:
Örnek 4 - Duruk değer olarak yorumlu metin kullanımı
<?php
// Duruk değişkenler
function foo()
{
static $bar = <<<LABEL
Burada hiçbir şey yok...
LABEL;
}
// Sınıf özellikleri ve sabitleri
class foo
{
const BAR = <<<FOOBAR
Sınıf sabiti örneği
FOOBAR;
public $baz = <<<FOOBAR
Özellik örneği
FOOBAR;
}
?>
PHP 5.3.0 ile ayrıca, yorumlu metinlerin bildiriminde çift tırnak kullanımı olasılığı da dikkate alınmıştır:
Örnek 5 - Yorumlu metin bildiriminde çift tırnak kullanımı
<?php
echo <<<"TIRNAKLI"
Merhaba Dünya!
TIRNAKLI;
?>
Bilginize:
Yorumlu metin desteği PHP 4'te eklenmiştir.
Yorumsuz metinler
Yorumlu metinlerin çift tırnaklı dizgelere karşılık gelmesi gibi yorumsuz metinler de tek tırnaklı dizgelere karşılık gelir. Yorumsuz metinler de yorumlular gibi belirtilir ama, yorumsuz metin içinde çözümleme yapılmaz. Yorumsuz metinler, PHP kodlarını veya büyük metin bloklarını herhangi bir önlem almaksızın içine yerleştirmek için elverişlidirler. Belirtilen metin bloğunun çözümlenmemesinden dolayı SGML'nin <![CDATA[ ]]> oluşumu ile benzer özelliklere sahiptir.
Yorumsuz metin de yorumlu metindeki <<< dizgesini kullanır fakat betimleyicisi tek tırnak içine alınır; yani, şuna benzer: <<<'EOT'. Yorumlu metin için geçerli tüm diğer kurallar yorumsuz metin için de geçerlidir; özellikle de kapanış betimleyici ile ilgili olanlar.
Örnek 6 - Yorumsuz metin örneği
<?php
$str = <<<'EOD'
Yorumlu metin sözdizimi
kullanılarak çok sayıda
satıra bölünmüş dizge örneği.
EOD;
/* Değişkenli daha karmaşık bir örnek. */
class foo
{
public $foo;
public $bar;
function foo()
{
$this->foo = 'Foo';
$this->bar = array('Bar1', 'Bar2', 'Bar3');
}
}
$foo = new foo();
$name = 'Kimimben';
echo <<<'EOT'
İsmim "$name" ve işim $foo->foo basmak.
Artık {$foo->bar[1]} basıyorum.
Bu büyük 'A' basmalı: \x41
EOT;
?>
Yukarıdaki örneğin çıktısı:
İsmim "$name" ve işim $foo->foo basmak.
Artık {$foo->bar[1]} basıyorum.
Bu büyük 'A' basmalı: \x41Bilginize:
Yorumlu metinlerin aksine yorumsuz metinler herhangi bir duruk veri bağlamında kullanılabilirler. Sınıf özelliklerini veya sabitlerini yorumsuz metin kullanarak ilklendirme örneği:
Örnek 7 - Duruk veri örneği
<?php
class foo {
public $bar = <<<'EOT'
bar
EOT;
}
?>
Bilginize:
Yorumlu metin desteği PHP 5.3.0'da eklenmiştir.
Değişken çözümleme
Bir dizge çift tırnaklar arasında veya bir yorumlu metin olarak belirtilmişse içindeki değişkenler çözümlenir.
İki sözdizimi türü vardır: Biri basit, diğeri karmaşık. Basit sözdizimi en çok kullanılanı ve elverişli olanıdır; bir değişken, bir dizi değeri veya bir nesne özelliğini bir dizge içinde en az çabayla kullanmayı sağlar.
Karmaşık sözdizimi PHP4'ten itibaren kullanılmakta olup ifadeyi sarmalayan kaşlı ayraçlar biçiminde kendini gösterir.
Basit Sözdizimi
Çözümleyici, bir dolar imine ($) rastlandığında, geçerli bir değişken ismi oluşturmak için alabildiği bütün dizgecikleri açgözlülükle toplar. Değişken isminin kaşlı ayraçlar arasına alınması ismin sonunun açıkça belirtilmesini sağlar.
<?php
$bira = 'Bira';
echo "$bira'nın tadı berbattır"; // çalışır; "'" değişken adında geçersizdir
echo "$biralar geldi"; // çalışmaz; 'lar' değişken isminde geçerlidir
// ama değişken "$biralar" değildir.
echo "${bira}lar geldi"; // çalışır
echo "{$bira}lar geldi"; // çalışır
?>
Bir dizi indisi veya bir nesne özelliği de benzer şekilde çözümlenebilir. Dizi indislerinde indis sonunu, kapayan köşeli ayraç (]) belirler. Aynı kural, basit değişkenler olarak nesne özelliklerine de uygulanır.
<?php
// Bu örnekler dizge içinde dizi kullanımına özgüdür.
// Dizilerin dizgesel anahtarları daima tırnak içine alınır,
// bu amaçla kaşlı ayraçlar kullanılmaz.
// Bütün hataları görelim
error_reporting(E_ALL);
$meyve = array('çilek' => 'kırmızı', 'muz' => 'sarı');
// Çalışır, fakat bunun dizge dışında farklı çalışacağına dikkat edin
echo "Bir muz $meyve[muz] renktedir.";
// Çalışır
echo "Bir muz {$meyve['muz']} renktedir.";
// çalışır, fakat PHP aşağıda açıklandığı gibi önce muz adında bir sabit arar
echo "Bir muz {$meyve[muz]} renktedir.";
// Çalışmaz, kaşlı ayraç kullanın. Bir çözümleme hatasına yol açar.
echo "Bir muz $meyve['muz'] renktedir.";
// Çalışır
echo "Bir muz " . $meyve['muz'] . " renktedir.";
// Çalışır
echo "Bu karenin bir kenarı $square->width metre uzunluktadır.";
// Çalışmaz. Çözüm için karmaşık sözdizimine bakın.
echo "Bu karenin bir kenarı $square->width00 santimetre uzunluktadır.";
?>
Bunlardan daha karmaşık herşey için karmaşık sözdizimini kullanmalısınız.
Karmaşık (kaşlı ayraçlı) sözdizimi
Buna karmaşık denmesinin sebebi sözdiziminin karmaşıklığı değil, karmaşık ifadelerin kullanımını mümkün kılmasıdır.
Aslında, isim alanındaki her değer, bir dizge içinde bu sözdizimi ile yer alabilir. İfade basitçe dizge dışındaki gösterimiyle yazılıp { ve } arasına alınır. { öncelenemeyeceğinden bu sözdizimi sadece $ iminin { iminin hemen ardında yer aldığı durumlarda tanınır. {\$ kullanımı bir sayıl {$ alınmasıyla sonuçlanır. Bazı örnekler:
<?php
// Tüm hataları görelim
error_reporting(E_ALL);
$şahane = 'harika';
// Çalışmaz, çıktısı: Bu çok { harika}
echo "Bu çok { $şahane}";
// Çalışır, çıktısı: Bu çok harika
echo "Bu çok {$şahane}";
echo "Bu çok ${şahane}";
// Çalışır
echo "Bu karenin bir kenarı {$square->width}00 santimetre uzunluktadır.";
// Çalışır
echo "Bu çalışır: {$arr[4][3]}";
// $foo[bar] bir dizge dışında neden yanlışsa bu da o yüzden yanlıştır.
// Yani, bu yine de çalışır fakat PHP önce foo adında bir sabit
// arayacağından çalışır; bununla birlikte E_NOTICE seviyesinde
// bir hata oluşacaktır (tanımsız sabit).
echo "Bu yanlış: {$arr[foo][3]}";
// Çalışır. Çok boyutlu dizileri dizgelerin içinde kullanılırken,
// dizileri daima kaşlı ayraçlar arasına alın.
echo "Bu çalışır: {$arr['foo'][3]}";
// Çalışır.
echo "Bu çalışır: " . $arr['foo'][3];
echo "Bu da çalışır: {$obj->values[3]->name}";
echo "$name adlı değişkenin değeri: {${$name}}";
echo "Adı getName() işlevinin dönüş değeri olan değişkenin değeri: {${getName()}}";
echo "Adı \$object->getName() yönteminin dönüş değeri olan değişkenin değeri: {${$object->getName()}}";
?>
Bu sözdizimini kullanan dizgeler içindeki değişkenler üzerinden de sınıf özelliklerine erişmek mümkündür.
<?php
class foo {
var $bar = 'I am bar.';
}
$foo = new foo();
$bar = 'bar';
$baz = array('foo', 'bar', 'baz', 'quux');
echo "{$foo->$bar}\n";
echo "{$foo->$baz[1]}\n";
?>
Yukarıdaki örneğin çıktısı:
I am bar.
I am bar.
Bilginize:
İşlev ve yöntem çağrılarının, duruk sınıf değişkenlerinin ve sınıf sabitlerinin {$} içinde çağrılması PHP 5'ten beri çalışmaktadır. Erişilen değer, dizgenin tanımlandığı etki alanındaki bir değişkenin ismi olarak yorumlanır. Kaşlı ayraçların tek başına kullanımı ({}), duruk sınıf değişkenlerinin veya sınıf sabitlerinin değerlerine veya işlev ve yöntemlerin dönüş değerlerine erişim için kullanılmaz.
<?php
// Tüm hatalar gösterilsin.
error_reporting(E_ALL);
class beers {
const softdrink = 'rootbeer';
public static $ale = 'ipa';
}
$rootbeer = 'A & W';
$ipa = 'Alexander Keith\'s';
// Bu çalışır; çıktısı: I'd like an A & W
echo "I'd like an {${beers::softdrink}}\n";
// Bu da çalışır; çıktısı: I'd like an Alexander Keith's
echo "I'd like an {${beers::$ale}}\n";
?>
Dizge erişimi ve karaktere göre değişiklik
Dizgelerin içindeki karakterlere, dizilerin köşeli ayraçları arasında karakterin dizinin başlangıcından itibaren (ilk karakterin indisi sıfır olmak üzere) kaçıncı karakter olduğu belirtilerek ($dizge[42] gibi) erişilebilir veya o karakterde değişiklik yapılabilir. Dizgeler bu nedenle bir karakter dizisi olarak düşünülür. 1 karakterden fazlasını elde etmek veya yer değiştirmek isterseniz substr() ve substr_replace() işlevlerini kullanabilirsiniz.
Bilginize: Dizge karakterlerine ayrıca $str{42} biçeminde kaşlı ayraçlar kullanılarak da erişilebilirse de bu sözdiziminin kullanımı PHP 5.3.0 itibariyle önerilmemektedir. Bu amaçla kaşlı ayraçları değil, daima köşeli ayraçları tercih edin; örnek: $str[42].
Karakter indisi olarak dizgenin uzunluğundan büyük bir değer belirtmek,
dizgenin sonuna boşlukların eklenmesine sebep olur. Tamsayı olmayan
indis değerleri tamsayıya dönüştürülür. Kuraldışı indis belirtimi
E_NOTICE'e sebep olur. Yazma sırasında negatif
indisler bir E_NOTICE çıktılanmasına sebep olurken
okuma işlemi boş dizge okunmasıyla sonuçlanır. Atanmış bir dizgenin
sadece ilk karakteri kullanılır. Boş dizge atamak NULL atamasıyla
sonuçlanır.
Örnek 8 - Bazı dizge örnekleri
<?php
// Dizgenin ilk karakterini alalım
$str = 'This is a test.';
$first = $str[0];
// Dizgenin üçüncü karakterini alalım
$third = $str[2];
// Dizgenin son karakterini alalım
$str = 'This is still a test.';
$last = $str[strlen($str)-1];
// Dizgenin son karakterini değiştirelim
$str = 'Look at the sea';
$str[strlen($str)-1] = 'e';
?>
Bilginize:
Diğer türlerdeki değişkenlere [] veya {} kullanarak erişme çabası
NULLdönmesiyle sonuçlanır.
Kullanışlı işlevler ve işleçler
Dizgeler '.' (nokta) işleci kullanılarak ardarda eklenebilir. '+' (toplama) işlecinin bu amaçla kullanımının yararsız oluşuna dikkat ediniz. Daha ayrıntılı bilgi edinmek için Dizge İşleçleri belgesine bakınız.
Dizgelerde değişiklik yapmak için çok sayıda yararlı işlev mevcuttur.
Genel işlevler için Dizge İşlevlerine, ileri düzey bul ve değiştir işlevselliği için düzenli ifade işlevlerine veya Perl uyumlu düzenli ifade işlevlerine bakınız.
Ayrıca, URL dizgeleri için işlevler ve dizgeleri şifrelemek veya şifrelerini çözmek için mcrypt ve mhash işlevleri vardır.
Son olarak, karakter türü işlevlerine de bakabilirsiniz.
Dizgeye dönüşüm
Bir değer bir dizgeye (string) tür çarpıtması veya strval() işleviyle dönüştürülür. Bir dizgenin gerekli olduğu ifade bağlamlarında dizgeye dönüşüm özdevinimli olarak gerçekleşir. Bu genellikle, echo veya print işlevleri kullanılırken veya bir değişken bir dizge ile karşılaştırılırken gerçekleşir. Aşağıdakilere, Türler ve Tür Dönüşümü bölümlerinde daha ayrıntılı değinilmiştir. Ayrıca, settype() işlevine de bakabilirsiniz.
boolean türündeki TRUE değeri string
türündeki "1" değerine dönüştürülür.
boolean türündeki FALSE değeri string
türündeki "" değerine (boş dizgeye) dönüştürülür. Bu
şekilde, boolean ve string değerler arasında
her iki yönde de dönüşüm yapılabilmektedir.
integer veya float türünde bir değerin string türüne dönüşümü sayının dizgesel gösterimiyle (üstel gösterim dahil) sonuçlanır. Kayan noktalı sayılar üstel gösterim kullanılarak dönüştürülebilir (4.1E+6 gibi).
Bilginize:
Ondalık nokta karakteri betiğin çalıştığı yerele (LC_NUMERIC) özgüdür. Bakınız: setlocale() işlevi.
Diziler daima "Array" dizgesine dönüştürülür; bundan dolayı echo ve print bir dizinin içeriğini kendiliklerinden gösteremezler. Tek bir dizi elemanını görüntüleyebilmek için echo $arr['foo'] gibi bir oluşum kullanınız. İçeriğin tamamının görüntülenebilmesiyle ilgili ipuçları için aşağıya bakınız.
object türler PHP 4'te daima "Object" dizgesine dönüştürülür. Nesne özelliklerinin değerlerini hata ayıklama amacıyla basmak için aşağıdaki paragrafı okuyunuz. Nesne sınıfının ismini öğrenmek için get_class() işlevini kullanınız. PHP 5 itibariyle, uygulanabildiği takdirde, __toString yöntemi kullanılır.
resource türler daima "Resource id #1" benzeri bir dizgeye dönüştürülürler; buradaki 1, özkaynağa PHP tarafından çalışma anında atanan eşsiz bir sayıdır. Bu yapıya güvenmeseniz iyi olur; ilerde değişebilir. Özkaynağın türünü öğrenmek için get_resource_type() işlevini kullanınız.
NULL daima boş bir dizgeye dönüştürülür.
Yukarıda bahsedildiği gibi, bir diziyi, nesneyi veya özkaynağı doğrudan dönüştürmek, bunların değerleri hakkında işe yarar hiçbir bilgi sağlamaz. Bu tür içerikleri daha verimli şekilde incelemek isterseniz print_r() ve var_dump() işlevlerine bakınız.
Çoğu PHP değeri kalıcı olarak saklamak amacıyla dizgelere dönüştürülebilir. Bu yönteme dizgeleştirme adı verilir ve serialize() işlevi tarafından gerçekleştirilir. Eğer PHP motoru WDDX desteğiyle derlenmişse PHP değerleri ayrıca iyi biçimli XML metin olarak da dizgeleştirilebilir.
Dizgelerin sayılara dönüşümü
Bir dizge, sayısal bir bağlamda değerlendirildiğinde sonuçlanacak değer ve türün nasıl belirleneceği aşağıda açıklanmıştır.
Dizge, '.', 'e' veya 'E' karakterlerini içermiyorsa ve sayısal değeri
PHP_INT_MAX ile tanımlanan genişlikte bir tamsayı
ise string tür bir integer tür olarak, aksi
takdirde bir float olarak değerlendirilir.
Değerin dizgenin başında belirtileceği varsayılır. Eğer dizge geçerli bir sayısal veri ile başlıyorsa sayısal değer olarak bu kullanılır. Aksi takdirde değer 0 (sıfır) olacaktır. Geçerli sayısal veri isteğe bağlı bir işaret ile başlar, bir veya daha fazla sayıda rakam ile isteğe bağlı bir ondalık nokta içerebilir ve isteğe bağlı bir üstel gösterimle sona erer. Üs, 'e' veya 'E' harfini takibeden bir veya daha fazla rakamdan oluşur.
<?php
$foo = 1 + "10.5"; // $foo float'tır (11.5)
$foo = 1 + "-1.3e3"; // $foo float'tır (-1299)
$foo = 1 + "bob-1.3e3"; // $foo integer'dir (1)
$foo = 1 + "bob3"; // $foo integer'dir (1)
$foo = 1 + "10 Small Pigs"; // $foo integer'dir (11)
$foo = 4 + "10.2 Little Piggies"; // $foo float'tır (14.2)
$foo = "10.0 pigs " + 1; // $foo float'tır (11)
$foo = "10.0 pigs " + 1.0; // $foo float'tır (11)
?>
Bu dönüşüm nakkında daha ayrıntılı bilgi edinmek için strtod(3) Unix kılavuz sayfasına bakınız.
Bu bölümdeki örneklerden birini denemek isterseniz örnekleri kopyala/yapıştır yöntemiyle aşağıdaki satıra yerleştirip neler olup bittiğini görebilirsiniz:
<?php
echo "\$foo==$foo; " . gettype ($foo) . " türündedir<br />\n";
?>
Tamsayıya dönüştürerek C'deki gibi bir karakterin kodunu alabilmeyi beklemeyin. Karakter/ASCII kod dönüşümleri için ord() ve chr() işlevlerini kullanınız.
The documentation does not mention, but a closing semicolon at the end of the heredoc is actually interpreted as a real semicolon, and as such, sometimes leads to syntax errors.
This works:
<?php
$foo = <<<END
abcd
END;
?>
This does not:
<?php
foo(<<<END
abcd
END;
);
// syntax error, unexpected ';'
?>
Without semicolon, it works fine:
<?php
foo(<<<END
abcd
END
);
?>
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
I recently discovered the joys of using heredoc with sprintf and positions. Useful if you want some code to iterate, you can repeat placeholders.
<?php
function getNumber($num = 0) {
$foo = rand(1,20);
return ($foo + $num);
}
function getString() {
$foo = array("California","Oregon","Washington");
shuffle($foo);
return $foo[0];
}
function getDiv() {
$num = getNumber();
$div = sprintf( "<div>%s</div>", getNumber(rand(-5,5)) );
return $div;
}
$string = <<<THESTRING
I like the state of %1\$s <br />
I picked: %2\$d as a number, <br />
I also picked %2\$d as a number again <br />
%3\$s<br />
%3\$s<br />
%3\$s<br />
%3\$s<br />
%3\$s<br />
THESTRING;
$returnText = sprintf( $string, getString(),getNumber(),getDiv() );
echo $returnText;
?>
Expected output of the above code:
I like the state of Oregon
I picked: 15 as a number,
I also picked 15 as a number again
5
5
5
5
5
Although current documentation says 'A string literal can be specified in four different ways: ...', actually there is a fifth way to specify a (binary) string:
<?php $binary = b'This is a binary string'; ?>
The above statement declares a binary string using the 'b' prefix, which is available since PHP 5.2.1. However, it will only have effect as of PHP 6.0.0, as noted on http://www.php.net/manual/en/function.is-binary.php .
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 . '"';
}
?>
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.
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);
If you want a parsed variable surrounded by curly braces, just double the curly braces:
<?php
$foo = "bar";
echo "{{$foo}}";
?>
will just show {bar}. The { is special only if followed by the $ sign and matches one }. In this case, that applies only to the inner braces. The outer ones are not escaped and pass through directly.
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)
?>
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;
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
Watch out for the "unexpected T_SL" error. This appears to occur when there is white space just after "<<<EOT" and since it's white space it's real hard to spot the error in your code.
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';
}
?>
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.
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"
*/
?>
Leading zeroes in strings are (least-surprise) not treated as octal.
Consider:
$x = "0123" + 0;
$y = 0123 + 0;
echo "x is $x, y is $y"; //prints "x is 123, y is 83"
in other words:
* leading zeros in numeric literals in the source-code are interpreted as "octal", c.f. strtol().
* leading zeros in strings (eg user-submitted data), when cast (implicitly or explicitly) to integer are ignored, and considered as decimal, c.f. strtod().
Here is an easy hack to allow double-quoted strings and heredocs to contain arbitrary expressions in curly braces syntax, including constants and other function calls:
<?php
// Hack declaration
function _expr($v) { return $v; }
$_expr = '_expr';
// Our playground
define('qwe', 'asd');
define('zxc', 5);
$a=3;
$b=4;
function c($a, $b) { return $a+$b; }
// Usage
echo "pre {$_expr(1+2)} post\n"; // outputs 'pre 3 post'
echo "pre {$_expr(qwe)} post\n"; // outputs 'pre asd post'
echo "pre {$_expr(c($a, $b)+zxc*2)} post\n"; // outputs 'pre 17 post'
// General syntax is {$_expr(...)}
?>
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"
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
Just want to mention that if you want a literal { around a variable within a string, for example if you want your output to be something like the following:
{hello, world}
and all that you put inside the {} is a variable, you can do a double {{}}, like this:
$test = 'hello, world';
echo "{{$test}}";
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'
If you need to emulate a nowdoc in PHP < 5.3, try using HTML mode and output capturing. This way '$' or '\n' in your string won't be a problem anymore (but unfortunately, '<?' will be).
<?php
// Start of script
ob_start(); ?>
A text with 'quotes'
and $$$dollars$$$.
<?php $input = ob_get_contents(); ob_end_clean();
// Do what you want with $input
echo "<pre>" . $input . "</pre>";
?>
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.
Empty strings seem to be no real strings, because they behave different to strings containing data. Here is an example.
It is possible to change a character at a specific position using the square bracket notation:
<?php
$str = '0';
$str[0] = 'a';
echo $str."\n"; // => 'a'
?>
It is also possible to change a character with does not exist, if the index is "behind" the end of the string:
<?php
$str = '0';
$str[1] = 'a';
echo $str."\n"; // => 0a
?>
But if you do that on an empty string, the string gets silently converted into an array:
<?php
$str = '';
$str[0] = 'a';
echo $str."\n"; // => Array
?>
Expectedly <?php $string[$x] ?> and <?php substr($string, $x, 1) ?> will yield the same result... normally!
However, when you turn on the Function Overloading Feature (http://php.net/manual/en/mbstring.overload.php), this might not be true!
If you use this Overloading Feature with 3rd party software, you should check for usage of the String access operator, otherwise you might be in for some nasty surprises.
Heredoc literals delete any trailing space (tabs and blanks) on each line. This is unexpected, since quoted strings do not do this. This is probably done for historical reasons, so would not be considered a bug.
Regarding the lack of complex expression interpolation, just assign an identity function to a variable and call it:
function id($arg) { return $arg; }
$expr = id;
echo "Field is: {$expr( "1 ". ucfirst('whatzit')) }";
It is slower due to an additional function call, but it does avoid the assignment of a one-shot temporary variable. When there are a lot of very simple value transformations made just for display purposes, it can de-clutter code.
I commented on a php bug feature request for a string expansion function and figured I should post somewhere it might be useful:
using regex, pretty straightforward:
<?php
function stringExpand($subject, array $vars) {
// loop over $vars map
foreach ($vars as $name => $value) {
// use preg_replace to match ${`$name`} or $`$name`
$subject = preg_replace(sprintf('/\$\{?%s\}?/', $name), $value,
$subject);
}
// return variable expanded string
return $subject;
}
?>
using eval() and not limiting access to only certain variables (entire current symbol table including [super]globals):
<?php
function stringExpandDangerous($subject, array $vars = array(), $random = true) {
// extract $vars into current symbol table
extract($vars);
$delim;
// if requested to be random (default), generate delim, otherwise use predefined (trivially faster)
if ($random)
$delim = '___' . chr(mt_rand(65,90)) . chr(mt_rand(65,90)) . chr(mt_rand(65,90)) . chr(mt_rand(65,90)) . chr(mt_rand(65,90)) . '___';
else
$delim = '__ASDFZXCV1324ZXCV__'; // button mashing...
// built the eval code
$statement = "return <<<$delim\n\n" . $subject . "\n$delim;\n";
// execute statement, saving output to $result variable
$result = eval($statement);
// if eval() returned FALSE, throw a custom exception
if ($result === false)
throw new EvalException($statement);
// return variable expanded string
return $result;
}
?>
I hope that helps someone, but I do caution against using the eval() route even if it is tempting. I don't know if there's ever a truely safe way to use eval() on the web, I'd rather not use it.
Hi.
I noticed that the documentation does not mention that when you have an XML element which contains a dash (-) in its name can only be accessed using the bracelets notation.
For example:
<xml version="1">
<root>
<element-one>value4element-one</element-one>
</root>
to access the above 'element-one' using SimpleXML you need to use the following:
$simpleXMLObj->root->{'element-one'}
to retrieve the value.
Hope this helps,
Denis R.
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>";
?>
If you require a NowDoc but don't have support for them on your server -- since your PHP version is less than PHP 5.3.0 -- and you are in need of a workaround, I'd suggest using PHP's __halt_compiler() which is basically a knock-off of Perl's __DATA__ token if you are familiar with it.
Give this a run to see my suggestion in action:
<?php
//set $nowDoc to a string containing a code snippet for the user to read
$nowDoc = file_get_contents(__FILE__,null,null,__COMPILER_HALT_OFFSET__);
$nowDoc=highlight_string($nowDoc,true);
echo <<<EOF
<!doctype html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>NowDoc support for PHP < 5.3.0</title>
<meta name="author" content="Ultimater at gmail dot com" />
<meta name="about-this-page"
content="Note that I built this code explicitly for the
php.net documenation for demonstrative purposes." />
<style type="text/css">
body{text-align:center;}
table.border{background:#e0eaee;margin:1px auto;padding:1px;}
table.border td{padding:5px;border:1px solid #8880ff;text-align:left;
background-color:#eee;}
code ::selection{background:#5f5color:white;}
code ::-moz-selection{background:#5f5;color:white;}
a{color:#33a;text-decoration:none;}
a:hover{color:rgb(3,128,252);}
</style>
</head>
<body>
<h1 style="margin:1px auto;">
<a
href="http://php.net/manual/en/language.types.string.php#example-77">
Example #8 Simple syntax example
</a></h1>
<table class="border"><tr><td>
$nowDoc
</td></tr></table></body></html>
EOF;
__halt_compiler()
//Example code snippet we want displayed on the webpage
//note that the compiler isn't actually stopped until the semicolon
;<?php
$juices = array("apple", "orange", "koolaid1" => "purple");
echo "He drank some $juices[0] juice.".PHP_EOL;
echo "He drank some $juices[1] juice.".PHP_EOL;
echo "He drank some juice made of $juice[0]s.".PHP_EOL; // Won't work
echo "He drank some $juices[koolaid1] juice.".PHP_EOL;
class people {
public $john = "John Smith";
public $jane = "Jane Smith";
public $robert = "Robert Paulsen";
public $smith = "Smith";
}
$people = new people();
echo "$people->john drank some $juices[0] juice.".PHP_EOL;
echo "$people->john then said hello to $people->jane.".PHP_EOL;
echo "$people->john's wife greeted $people->robert.".PHP_EOL;
echo "$people->robert greeted the two $people->smiths."; // Won't work
?>
The docs say: "Heredoc text behaves just like a double-quoted string, without the double quotes" but there is a notable hidden exception to that rule: the final newline in the string (the one before closing heredoc token) is elided. i.e. if you have:
$foo = <<<EOF
a
b
c
EOF;
the result is equivalent to "a\nb\nc", NOT "a\nb\nc\n" like the docs imply.
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.
An interesting finding about Heredoc "syntax error, unexpected $end".
I got this error because I did not use the php close tag "?>" and I had no code after the heredoc code.
foo1.php code gives "syntax error, unexpected $end".
But in foo2.php and foo3.php, when you add a php close tag or when you have some more code after heredoc it works fine.
Example Code:
foo1.php
1. <?php
2. $str = <<<EOD
3. Example of string
4. spanning multiple lines
5. using heredoc syntax.
6. EOD;
7.
foo2.php
1. <?php
2. $str = <<<EOD
3. Example of string
4. spanning multiple lines
5. using heredoc syntax.
6. EOD;
7.
8. echo $str;
9.
foo3.php
1. <?php
2. $str = <<<EOD
3. Example of string
4. spanning multiple lines
5. using heredoc syntax.
6. EOD;
7. ?>
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.
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;
?>
