Here's a function to recursively convert objects to arrays and remove the special characters from private and protected variables. I use it with XML_Serializer to convert objects to XML.
<?php
function object_to_array($mixed) {
if(is_object($mixed)) $mixed = (array) $mixed;
if(is_array($mixed)) {
$new = array();
foreach($mixed as $key => $val) {
$key = preg_replace("/^\\0(.*)\\0/","",$key);
$new[$key] = object_to_array($val);
}
}
else $new = $mixed;
return $new;
}
?>
array
PHP'de bir dizi aslında sıralı bir eşlemdir. Bir eşlem, değerleri anahtarlarla ilişkilendiren bir veri türüdür. Bu veri türü farklı kullanım amaçları için en iyilenebilir; bir dizi, bir yöneysel liste, bir isim-değer çiftleri tablosu, bir sözlük, bir nesne listesi, yığıt, kuyruk ve daha bir sürü başka şey olarak ele alınabilir. Dizilerin değerleri, ağaçlar, diziler ve hatta çok boyutlu diziler bile olabilir.
Tüm bu veri yapılarının açıklanması bu kılavuzun amacını aşar. Fakat, en azından her biri için birer örnek verilebilir. Bu konuda daha fazla bilgi edinmek için bu konuyla ilgili olarak yayımlanmış eserleri inceleyiniz.
Sözdizimi
Bir dizinin array() ile belirtilmesi
Bir dizi array() işlevi kullanılarak belirtilebilir. Değiştirge olarak, birbirlerinden virgüllerle ayrılmış çok sayıda anahtar => değer çifti alabilir.
array( anahtar => değer , ... ) // anahtar sadece integer veya string türünde olabilir. // değer herhangi bir türde herhangi bir değer olabilir.
<?php
$dizi = array("fu" => "bar", 12 => true);
echo $dizi["fu"]; // bar
echo $dizi[12]; // 1
?>
Bir anahtar ya integer ya da string türünde olabilir. Bir anahtar, sadece onluk tamsayı gösterimiyle belirtilmişse bir tamsayı anahtar olarak yorumlanır. Yani, "8" belirtilmeşse bu tamsayı 8 olarak ele alınacak ama "08" belirtilmişse dizge "08" olarak ele alınacaktır. float türünde belirtilen bir anahtar integer türüne aşağı yuvarlanır. PHP için indisli ve ilişkisel diziler, her ikisi de integer ve string türünde indisler içerebildiğinden aynı çeşitten dizilerdir.
değer herhangi bir PHP türünde herhangi bir değer olabilir.
Bilginize: Tanımlanmamış bir dizi anahtarına erişmeye çalışmakla tanımsız bir değişkene erişmeye çalışmak arasında fark yoktur: E_NOTICE seviyesinde bir hata iletisi çıktılanır ve sonuç NULL olur
<?php
$dizi = array("birdizi" => array(6 => 5, 13 => 9, "a" => 42));
echo $dizi["birdizi"][6]; // 5
echo $dizi["birdizi"][13]; // 9
echo $dizi["birdizi"]["a"]; // 42
?>
Bir anahtar belirtmeksizin bir değer atanıyorsa değer, mevcut tamsayı anahtarların en büyüğüne bir eklenerek elde edilen tamsayı anahtarlı elemana atanır. Bir anahtar mevcut anahtarlardan biriyle değer atıyorsa, yeni değer mevcut eleman değerinin üzerine yazılır.
<?php
// Bu iki dizi birbirinin aynıdır:
array(5 => 43, 32, 56, "b" => 12);
array(5 => 43, 6 => 32, 7 => 56, "b" => 12);
?>
PHP 4.3.0 öncesinde, en büyük indisi bir negatif tamsayı olan bir diziye anahtarsız değer atanması durumunda değere anahtarı yukarıda açıklandığı gibi atanırdı. PHP 4.3.0 ve sonrasında ise böyle bir durumda yeni değer 0 anahtarına atanmaktadır.
anahtar olarak TRUE belirtilirse bu tamsayı 1 olarak, FALSE belirtilirse tamsayı 0 olarak yorumlanır. anahtar olarak NULL kullanımı bir boş dizge olarak yorumlanır. Boş dizgeyle anahtar belirtimi, yeni değerin boş dizge anahtarlı olarak atanmasına sebep olur ve bu, anahtar belirtmeksizin (boş köşeli ayraçlarla) atama yapmak anlamında değerlendirilmez.
array veya object türünde anahtar belirtilemez. Aksi takdirde şöyle bir uyarı alırsınız: Illegal offset type (Kuraldışı konumlama türü).
Köşeli ayraçlarla atama ve değişiklik yapmak
Mevcut bir dizi, doğrudan değer atamak suretiyle değiştirilebilir.
Bu işlem, diziye köşeli ayraçlar arasında belirtilen bir anahtar kullanılarak değer atamak biçeminde yapılır. Diziye yeni bir değer atamak için köşeli ayraçlar boş olarak ([]) belirtilebilir.
$dizi[anahtar] = değer; $dizi[] = değer; // anahtar sadece integer veya string türünde olabilir. // değer herhangi bir türde herhangi bir değer olabilir.
$dizi mevcut değilse oluşturulur, dolayısıyla bu da yeni bir dizi oluşturma yöntemidir. Belli bir değeri değiştirmek için yeni değer elemana mevcut anahtar kullanılarak atanır. Belli bir elemanı (anahtar/değer çiftini) diziden silmek için unset() işlevi kullanılır.
<?php
$dizi = array(5 => 1, 12 => 2);
$dizi[] = 56; // Betiğin bu noktasında bu atama
// $dizi[13] = 56; ile aynıdır
$dizi["x"] = 42; // "x" anahtarlı yeni bir eleman atar
unset($dizi[5]); // Elemanı diziden siler
unset($dizi); // Dizinin tamamını siler
?>
Bilginize: Yukarıda değinildiği gibi, bir diziye yeni değeri bir anahtar belirtmeden atamak, mevcut en büyük tamsayı indisine bir eklenerek elde edilen anahtar kullanılarak gerçekleşir. Dizide henüz bir tamsayı indis yoksa anahtar olarak 0 (sıfır) kullanılır.
Dikkat ederseniz, dizinin mevcut olması halinde, yeni bir değer atamak için en büyük tamsayı indisli anahtar kullanmaya gerek yoktur. Buna sadece dizi yeniden indislenmişse gerek olabilir. Aşağıdaki örnek anlatımı pekiştirecektir:
<?php
// Basit bir dizi oluşturalım.
$dizi = array(1, 2, 3, 4, 5);
print_r($dizi);
// Şimdi bütün elemanları silelim ama dizi kalsın:
foreach ($dizi as $i => $value) {
unset($dizi[$i]);
}
print_r($dizi);
// Bir eleman ekleyelim (dikkat: yeni anahtar 0 değil 5 olacak!)
$dizi[] = 6;
print_r($dizi);
// Yeniden indisleyelim:
$dizi = array_values($dizi);
$dizi[] = 7;
print_r($dizi);
?>Yukarıdaki örneğin çıktısı:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 ) Array ( ) Array ( [5] => 6 ) Array ( [0] => 6 [1] => 7 )
Kullanışlı işlevler
Dizilerle çalışmak için kullanılabilecek işlevlerin tamamını Dizi İşlevleri bölümünde bulabilirsiniz.
Bilginize: unset() işlevi bir diziden anahtar silmeyi mümkün kılar. Ama bu silme işlemi dizinin yeniden indislenmesiyle sonuçlanmaz. Eğer silme işleminin gerçekten "sil ve kaydır" yapmasını istiyorsanız, anahtarı sildikten sonra array_values() işlevini kullanarak diziyi yeniden indislemelisiniz.
<?php
$a = array(1 => 'bir', 2 => 'iki', 3 => 'üç');
unset($a[2]);
/* Bu silme işlemi dizi şöyle tanımlanmış gibi sonuçlanacaktır:
$a = array(1 => 'bir', 3 => 'üç');
böyle DEĞİL:
$a = array(1 => 'bir', 2 =>'üç');
*/
$b = array_values($a);
// $b artık array(0 => 'bir', 1 =>'üç') olmuştur
?>
foreach denetim yapısı özellikle diziler için tasarlanmıştır. Diziler üzerinde hareket edilmesini kolaylaştırır.
Diziler ne yapar, ne yapmaz?
$foo[bar] niye yanlıştır?
Bir dizge sayıllı indis daima tırnak içinde kullanılır. Örneğin, $foo[bar] yanlışken $foo['bar'] doğrudur. Ama, neden? Eski betiklerde şu sözdizimine sıkça rastlanır:
<?php
$foo[bar] = 'düşman';
echo $foo[bar];
// ve saire
?>
Bu yanlıştır, ama çalışır. Bunun sebebi, bu kodun bir dizgeden ziyade tanımsız bir sabit (bar) belirtiyor olmasıdır. PHP ilerde şans eseri ismi aynı zamanda değeri olan bir sabit tanımlayabilir. PHP özdevinimli olarak bir çıplak dizgeyi (tırnak içine alınmamış bir dizgeyi), bu çıplak dizgeyi içeren bir dizgeye dönüştüreceğinden bu çalışır. Örneğin, bar isminde tanımlanmış bir sabit yoksa, PHP bar sabitine 'bar' dizgesini yerleştirecek ve bunu kullanacaktır.
Bilginize: Bu, "anahtarlar daima tırnak içine alınır" demek değildir. sabitleri ve değişkenleri tek tırnak içine almayın, çünkü o zaman yorumlanmazlar.
<?php
error_reporting(E_ALL);
ini_set('hataları_göster', true);
ini_set('html_hataları', false);
// Basit bir dizi:
$dizi = array(1, 2);
$sayaç = count($dizi);
for ($i = 0; $i < $sayaç; $i++) {
echo "\n$i indisi inceleniyor: \n";
echo "Kötü: " . $dizi['$i'] . "\n";
echo "İyi: " . $dizi[$i] . "\n";
echo "Kötü: {$dizi['$i']}\n";
echo "İyi: {$dizi[$i]}\n";
}
?>Yukarıdaki örneğin çıktısı:
0 indisi inceleniyor: Notice: Undefined index: $i in /dosya/yolu/betik.php on line 10 Kötü: İyi: 1 Notice: Undefined index: $i in /dosya/yolu/betik.php on line 12 Kötü: İyi: 1 1 indisi inceleniyor: Notice: Undefined index: $i in /dosya/yolu/betik.php on line 10 Kötü: İyi: 2 Notice: Undefined index: $i in /dosya/yolu/betik.php on line 12 Kötü: İyi: 2
Bu davranışla ilgili diğer örnekler:
<?php
// Tüm hataları görelim
error_reporting(E_ALL);
$dizi = array('meyve' => 'elma', 'sebze' => 'havuç');
// Doğru
print $dizi['meyve']; // elma
print $dizi['sebze']; // havuç
// Yanlış. Bu çalışır, fakat meyve tanımlanmamış bir sabit
// olmadığından E_NOTICE seviyesinde bir PHP hatası oluşur
//
// Notice: Use of undefined constant meyve - assumed 'meyve'...
print $dizi[meyve]; // elma
// Bu, neler olup bittiğini gösteren bir sabit tanımlar;
// 'sebze' değeri meyve sabitine atanır.
define('meyve', 'sebze');
// Şimdi farkı görelim
print $dizi['meyve']; // elma
print $dizi[meyve]; // havuç
// Bir dizge içinde olduğundan bu da doğrudur.
// Dizge içinde kalan sabitler, sabit olarak ele alınmazlar;
// dolayısıyla burada bir E_NOTICE oluşmaz.
print "Turfanda $dizi[meyve]"; // Turfanda elma
// Bir istisna: Dizge içinde kaşlı ayraç içine alınmış
// sabitler, sabit olarak ele alınırlar.
print "Turfanda {$dizi[meyve]}"; // Turfanda havuç
print "Turfanda {$dizi['meyve']}"; // Turfanda elma
// Bu çalışmaz ve şöyle bir çözümleme hatasıyla sonuçlanır:
// Parse error: parse error, expecting T_STRING' or T_VARIABLE' or T_NUM_STRING'
// Bu, dizgeler içindeki süper küresellere de uygulanır.
print "Turfanda $dizi['meyve']";
print "Turfanda $_GET['foo']";
// Ard arda eklemek de bir seçenektir
print "Turfanda " . $dizi['meyve']; // Turfanda elma
?>
error_reporting yönergesine E_NOTICE seviyesinden hataları gösterecek bir atama yapılırsa (örneğin, E_ALL atanarak), böyle kullanımlar hemen görünür duruma gelir. error_reporting yönergesinin öntanımlı değeriyle E_NOTICE seviyesinden hatalar gösterilmez.
Sözdizimi bölümünde değinildiği gibi, köşeli ayraçlar ('[' ve ']') içinde belirtilenlerin birer ifade olması gerekir. Yani, aşağıdaki gibi bir kod çalışacaktır:
<?php
echo $dizi[birişlev($bar)];
?>
Bu, bir işlevin dönüş değerinin dizi indisi olarak kullanımına bir örnektir. PHP kendi sabitlerini de tanır:
<?php
$error_descriptions[E_ERROR] = "Ölümcül bir hata oluştu";
$error_descriptions[E_WARNING] = "PHP bir uyarı verdi";
$error_descriptions[E_NOTICE] = "Bu sadece bilgilendirici bir uyarı";
?>
E_ERROR sabitinin de ilk örnekteki bar kadar geçerli bir betimleyici oluşuna dikkat ediniz. Fakat, E_ERROR eşittir 1, vb. olduğundan aşağıdaki örnek de aynı işi yapar:
<?php
$error_descriptions[1] = "Ölümcül bir hata oluştu";
$error_descriptions[2] = "PHP bir uyarı verdi";
$error_descriptions[8] = "Bu sadece bilgilendirici bir uyarı";
?>
O halde bunun nesi kötü?
Bilinmeyen bir gelecekte PHP ekibi başkalarının kodlarıyla çelişen bir
sabit, bir anahtar sözcük veya bir değişken eklemek isteyebilir.
Örneğin, empty ve default birer anahtar sözcük olduklarından bu amaçla
kullanılmaları yanlıştır.
Bilginize: Yinelemek gerekirse, çift tırnak imleri arasına alınmış bir dizge, dizi indisini tırnak içine almadığından geçerlidir; yani, "$foo[bar]" geçeridir. Yukarıdaki örnekleri bu gözle tekrar inceleyin ve ayrıca dizgelerin içinde değişken çözümleme bölümüne de bakın.
Diziye dönüşüm
integer, float, string, boolean veya resource türünde bir değeri array türünde bir değere dönüştürme işlemi, sıfır indisli bir elemana bu değerin atanması ile sonuçlanır. Başka bir deyişle, (array)$sayılDeğer ile array($sayılDeğer) arasında bir fark yoktur.
Bir object türü array türüne dönüştürme işlemi, elemanları nesnenin üyeleri olan bir dizi ile sonuçlanır. Anahtarlar, bir kaç istisnai durum dışında üyelerin isimleridir: Tamsayı özellikler erişilebilir değildir; private değişkenlerin önüne sınıf isimleri getirilir; public değişkenlerin önünde bir '*' olur. Diğer taraftan, başlarına birşeyler eklenmiş böyle değişkenlerin değerleri NULL olur. Bu durum beklenmedik davranışlara yol açabilir:
<?php
class A {
private $A; // Bu '\0A\0A' haline gelir.
}
class B extends A {
private $A; // Bu '\0B\0A' haline gelir.
public $AA; // Bu 'AA' haline gelir.
}
var_dump((array) new B());
?>
Bu örneğin çıktısı 'AA' isimli iki anahtar görüntülerse de onlardan birinin ismi aslında '\0A\0A''dır.
NULL, bir diziye dönüştürülmek istenirse sonuç boş bir dizi olur.
Karşılaştırma
Dizileri array_diff() işleviyle veya dizi işleçleri kullanılarak karşılaştırmak mümkündür.
Örnekler
PHP'nin array türü çok yeteneklidir. Bazı örnekler:
<?php
// Bu:
$a = array( 'renk' => 'kırmızı',
'lezzet' => 'tatlı',
'şekil' => 'yuvarlak',
'isim' => 'elma',
4 // anahtarı 0 olacaktır
);
$b = array('a', 'b', 'c');
// . . . buna tamamen eşdeğerdir:
$a = array();
$a['renk'] = 'kırmızı';
$a['lezzet'] = 'tatlı';
$a['şekil'] = 'yuvarlak';
$a['isim'] = 'elma';
$a[] = 4; // anahtarı 0 olacaktır
$b = array();
$b[] = 'a';
$b[] = 'b';
$b[] = 'c';
// Yukarıdaki kod çalıştırıldığında $a, array('renk' => 'kırmızı',
// 'lezzet' => 'tatlı', 'şekil' => 'yuvarlak', 'isim' => 'elma', 0 => 4)
// dizisiyle, $b ise array(0 => 'a', 1 => 'b', 2 => 'c') veya basitçe
// array('a', 'b', 'c') dizisiyle sonuçlanacaktır.
?>
Örnek 1 - array() kullanımı
<?php
// Özellik eşlemeli dizi
$map = array( 'sürüm' => 4,
'sistem' => 'Linux',
'dil' => 'english',
'kısaltma' => true
);
// tamamen sayısal anahtarlar
$dizi = array( 7,
8,
0,
156,
-10
);
// Bu, array(0 => 7, 1 => 8, ...) ile aynıdır
$geçişli = array( 10, // key = 0
5 => 6,
3 => 7,
'a' => 4,
11, // anahtar = 6 (en büyük tamsayı indis 5 idi)
'8' => 2, // anahtar = 8 (tamsayı!)
'02' => 77, // anahtar = '02'
0 => 12 // 10 değerinin üzerine 12 yazılacak
);
// boş dizi
$boş = array();
?>
Örnek 2 - Derlem
<?php
$renkler = array('Turuncu', 'Pembe', 'Mor', 'Turkuaz');
foreach ($renkler as $renk) {
echo "$renk rengi sever misiniz?\n";
}
?>
Yukarıdaki örneğin çıktısı:
Turuncu rengi sever misiniz? Pembe rengi sever misiniz? Mor rengi sever misiniz? Turkuaz rengi sever misiniz?
PHP5'ten beri dizi değerleri gönderimli aktarıldıklarından dizi değerlerini doğrudan değiştirmek mümkündür. Fakat arada bazı şeyler yapmak gerekir:
Örnek 3 - Derlem
<?php
<?php
$renkler = array('Turuncu', 'Pembe', 'Mor', 'Turkuaz');
// PHP 5
foreach ($renkler as &$renk) {
$renk = strtoupper($renk);
}
unset($renk); /* Aşağıdaki atamalarda $renk son
dizi elemanını değiştirmesin */
// Eski sürümü yeniden elde edelim
foreach ($renkler as $anahtar => $renk) {
$renkler[$anahtar] = strtoupper($renk);
}
print_r($renkler);
?>
Yukarıdaki örneğin çıktısı:
Array
(
[0] => TURUNCU
[1] => PEMBE
[2] => MOR
[3] => TURKUAZ
)
Bu örnekte dizi indisleri 1'den başlatılmaktadır.
Örnek 4 - İndisi 1'den başlatmak
<?php
$ilkçeyrek = array(1 => 'Ocak', 'Şubat', 'Mart');
print_r($ilkçeyrek);
?>
Yukarıdaki örneğin çıktısı:
Array
(
[1] => Ocak
[2] => Şubat
[3] => Mart
)
Örnek 5 - Diziyi doldurmak
<?php
// bir diziyi bir dizin'in içeriği ile dolduralım
$tutamak = opendir('.');
while (false !== ($dosya = readdir($tutamak))) {
$dosyalar[] = $dosya;
}
closedir($tutamak);
?>
Diziler sıralıdır. Sıralama çeşitli sıralama işlevleri ile değiştirilebilir. Daha fazla bilgi için Dizi İşlevleri bölümüne bakınız. Bir dizinin eleman sayısını öğrenmek için count()işlevi kullanılabilir.
Örnek 6 - Dizi elemanlarının sıraya sokulması
<?php
sort($dosyalar);
print_r($dosyalar);
?>
Bir dizinin elemanlarına her türlü değer atanabileceğinden başka bir dizi de atanabilir. Böylece iç içe ve çok boyutlu dizilerin oluşturulması mümkün olur.
Örnek 7 - İç içe ve çok boyutlu diziler
<?php
$yemişler = array ( "yemişler" => array ( "a" => "iğde",
"b" => "badem",
"c" => "ceviz"
),
"sayılar" => array ( 1,
2,
3,
4,
5,
6
),
"yuvalar" => array ( "birinci",
5 => "ikinci",
"üçüncü"
)
);
// Yukarıdaki dizinin değerlerinin kullanıldığı bazı örnekler
echo $yemişler["yuvalar"][5]; // "ikinci" basar
echo $yemişler["meyveler"]["a"]; // "iğde" basar
unset($yemişler["yuvalar"][0]); // "birinci" silinir
// Yeni bir çok boyutlu dizi oluşturalım
$meyveler["elma"]["yeşil"] = "ekşi";
?>
Dizi atamaları daima değerleri kopyalamak şeklinde gerçekleşir. Bir diziyi gönderimli olarak kopyalamak için gönderim işleci kullanılır.
<?php
$dizi1 = array(2, 3);
$dizi2 = $dizi1;
$dizi2[] = 4; // $dizi2 değişti,
// $dizi1 hala array(2, 3)
$dizi3 = &$dizi1;
$dizi3[] = 4; // şimdi $dizi1 ve $dizi3 aynı
?>
array
25-Oct-2009 01:16
20-Oct-2009 05:55
Just in case someone finds it usefull.
If you want to capitalize the first letter of each word in the array you could:
<?php
$myarray = array("one","two","three","four","etc..");
$map = array_map('ucfirst', $myarray);
$j = join(' , ', $map);
echo $j;
?>
This will return: One , Two , Three , Four , Etc..
Probably it's not worth of posting it, but just thought beginners might find it usefull.
02-Oct-2009 11:33
This is a modification of a function like this which works with two dimensional arrays. Pass a 2d array to this function and my function will return an array of the arrays with the specified key-value pair (specified by $key and $value).
<?php
function seekKey($array, $key, $value)
{
$ret = array();
for ($i=0;$i<count($array);$i++)
{
if ($array[$i][$key]==$value)
$ret[] = $array[$i];
}
return $ret;
}
?>
28-Sep-2009 06:04
You can actually create arrays in arrays; just consider the following code:
<?php
function LoadData($file)
{
$lines = file($file) or die('Could not open file');
foreach($lines as $line)
{
$i[] = array($line);
print_r($i[1])
}
LoadData('file.csv');
?>
A (.csv-)file is loaded into the function LoadData and stored in the array $lines. Then foreach puts the values from the $lines-array into $line and $i is defined as an array of the array $line. Please note that this type of code could take up much of CPU-usage; it generates a multi-dimensional array.
When $i is printed (in the example, value 1 of the array) it would display:
Array ( [0] => Array (
[0] => 7;75;X;0;0;1;0;3;Gr;Br;Do;0;0;0;0;0;0;0;0;
[1] => ;200;K;0;0;0;0;0;Gr;0;0;0;0;ZL;0;0;0;0;0;
[2] => ;260;Z;;;;;;Gr;;;;;VL;;;;;;
[3] => ;270;K;;;;1;;Gr;Br;Li;;;;;;;;;
[4] => ;500;V;;;;;;Br;;;;;;;;;;;
[5] => 6;60;X;;;;;;;;;;;;;;;;;
[6] => ;80;K;;;;;;Gr;;;;;ZL;;;;;;
[7] => ;210;Z;;;;;;Gr;;;;;;;;;;;
)
13-Jul-2009 04:12
Note for PHP 5.3 changed behavior in 'erroneous' array creation:
Prior to PHP 5.3, this array definition (note the duplicate key):
<?php $a = array ('foo' => 1, 'bar' => 2, 'foo' => 3); ?>
Would create the following array:
array(
'foo' => 3,
'bar' => 2
)
So the /second/ key in the duplicate would override the first declaration.
Now with PHP 5.3, the following array will be created:
array(
'foo' => 1,
'bar' => 2
)
So the second duplicate key would be ignored.
Note that the array declaration indeed contains an error, but if your legacy code contains such array declaration, you will be hurt because of the changed behavior.
05-May-2009 02:47
A simple function to check if you can use your variable as an array offset validly and without getting it typecasted.
<?php
function is_safe_offset($offset) {
return array_pop(@array_flip(array($offset => 0))) === $offset;
}
$a = 8;
var_dump(is_safe_offset($a)); // true
$b = '8';
var_dump(is_safe_offset($b)); // false
$c = '08';
var_dump(is_safe_offset($c)); // true
$d = 'foo';
var_dump(is_safe_offset($d)); // true
$e = 3.8;
var_dump(is_safe_offset($e)); // false
$f = false;
var_dump(is_safe_offset($f)); // false
$g = null;
var_dump(is_safe_offset($g)); // false
$h = array();
var_dump(is_safe_offset($h)); // false
$i = new StdClass;
var_dump(is_safe_offset($i)); // false
?>
07-Mar-2009 12:41
Hello,
to check if an element was set is actually pretty simple:
<?php
$array = ('first' => 1,
'sec' => 2
);
$out = (isset($array['third'])) ? $array['third'] : 'third not set...';
echo $out;
?>
greets,
genix
17-Dec-2008 11:09
Trying to get array element that was not set, throws ERROR_NOTICE and returns NULL. Example:
<?php /* php v.4.4.7 */
$array = array(
'apple' => 'green',
'orange' => 'orange',
);
$pear_color = $array['pear']; // Notice: Undefined index: pear in /path/to/file.php on line 123
var_dump($pear_color); // NULL
?>
Haven't found that mentioned on this page.
24-Oct-2008 03:58
Note that NULL is not exactly a scalar value, so the following two lines of code do NOT produce identical arrays.
<?php
$x = (array) null; // $x ends up an empty array (zero elements)
$y = array(null); // $y ends up an array containing one element (a null)
?>
13-Sep-2008 03:49
Re: fmouse,
the phenomenom you're describing pertains to superglobals, not arrays, and it only applies in a very specific scope. Check out http://de.php.net/manual/en/language.variables.variable.php :
"Please note that variable variables cannot be used with PHP's Superglobal arrays within functions or class methods. The variable $this is also a special variable that cannot be referenced dynamically."
04-Jun-2008 11:43
>fmouse
Variable variables can be used with arrays as discussed in the variable variable section.
Also, from your code, $somevar can be an array and still work fine.
$fum = "somevar";
$$fum = array(); // $somevar is now an array
$foo = $$fum;
print_r( $foo); // we get an empty array printed
print_r() doesn't just print arrays, it prints any variable type.
If you pass it a variable, that hasn't been defined yet, it won't know how to print it.
You would get this same results by passing any undefined variable such as:
print_r( $bar ); // PHP Notice: undefined variable ...$bar
29-Apr-2008 08:14
Using variables as array names no longer works in PHP5.
$fum = "somevar";
$foo = $$fum;
# Still works if $somevar isn't an array. $foo contains the value of $somevar
but ....
$fum = "_POST";
print_r($$fum);
print_r(${$fum});
Neither form of indirection works in this context. $$fum comes back empty.
If you have PHP4 code that used this kind of indirection you can work around the change in PHP5 using an eval().
$fum = "_POST";
$foo = eval("return $$fum;");
print_r($foo);
This works!
18-Mar-2008 09:52
Sorting double dimensional arrays by a specified key bothe for Strings and for integers:
Ex:
$personDetails = array( array("firstName" => "Nancy", "lastName" => "Grace", "age" => 22), array("firstName" => "Andy", "lastName" => "Peter", "age" => 28), array("firstName" => "Jim", "lastName" => "Gary", "age" => 25), array("firstName" => "Lary", "lastName" => "James", "age" => 28), array("firstName" => "Peter", "lastName" => "David", "age" => 17), array("firstName" => "Raj", "lastName" => "King", "age" => 9), array("firstName" => "John", "lastName" => "Baxter","age" => 35) );
//To sort the array by firstName:-
function sortFirstName($p1, $p2) {
return strnatcmp($p1['firstName'], $p2['firstName']);
}
usort($personDetails, 'sortFirstName');
//To sort by an integer Field
function sortByInteger(&$personDetails, $field) {
$sort = "return strnatcmp(\$p1['$field'], \$p2['$field']);";
usort($personDetails, create_function('$p1,$p2', $sort));
return $personDetails;
}
$personDetails = sortByInteger($personDetails, 'age');
//To sort the array in Descending order by a key, It can be done by adding "-" sign before strnatcmp() function.
I hope this helps
09-Jan-2008 04:00
"If you convert a NULL value to an array, you get an empty array."
This turns out to be a useful property. Say you have a search function that returns an array of values on success or NULL if nothing found.
$values = search(...);
Now you want to merge the array with another array. What do we do if $values is NULL? No problem:
$combined = array_merge((array)$values, $other);
Voila.
19-Dec-2007 12:25
z on 22-Apr-2005 12:10 wrote:
-----------------------------------------------
Here's a simple function to insert a value into some position in an array
<?php
function array_insert($array,$pos,$val)
{
$array2 = array_splice($array,$pos);
$array[] = $val;
$array = array_merge($array,$array2);
return $array;
}
?>
and now for example...
<?php
$a = array("John","Paul","Peter");
$a = array_insert($a,1,"Mike");
?>
Now $a will be "John","Mike","Paul","Peter"
-----------------------------------------------
Im learning to use PHP and reading about array_splice found that
<?php
function array_insert($array,$pos,$val)
{
$array2 = array_splice($array,$pos);
$array[] = $val;
$array = array_merge($array,$array2);
return $array;
}
$a = array("John","Paul","Peter");
$a = array_insert($a,1,"Mike");
print_r($a);
?>
would output the same as
<?php
$b = array("John","Paul","Peter");
array_splice($b,1,0,array("Mike"));
print_r($b);
?>
10-Oct-2007 09:14
<?php
//Simple Login Script using associative array.
//You may modify the codes and use $_POST['FORM_FIELD_DATA'] for your web-page.
//You may spice-up the codes with more form field validation & security features.
//$user_name=$_POST['user_name'];
//$password=$_POST['password'];
$test_user_name = 'michelle_smith'; //for testing purpose only
$test_password = 'msmith321'; //for testing purpose only
$user_name = $test_user_name;
$password = $test_password;
// here user_name is key and password is the value of an array..
// website owner has to add new user/site member manually in $login_array
$login_array = array(
'user_name' => 'password',
'alex_duff' => 'alx321',
'xena78' => 'xena321',
'dela_pena' => 'delp321',
'shawn_1981' => 'shw81',
'michelle_smith' => 'msmith321');
ksort ($login_array);
reset($login_array);
if (isset($login_array[$user_name]))
{
$pass_check = $login_array[$user_name];
if ($password === $pass_check)
{
echo "Welcome, $user_name!\n<br>"; //may redirect to specific webpage.
}
else
{
echo "Please try again!"; //may redirect to Error page.
}
}
else
{
echo "Please register with us. Thanks!"; //may redirect to registration page.
exit();
}
echo("\n<br>");
echo 'Thanks to Thies C. Arntzen, Stig Bakken, Shane Caraveo, Andi Gutmans, Rasmus Lerdorf, Sam Ruby, Sascha Schumann, Zeev Suraski, Jim Winstead, Andrei Zmievski for wonderful PHP!';
?>
06-Sep-2007 06:36
Its worth noting that there does not appear to be any functional limitations on the length or content of string indexes. The string indexes for your arrays can contain any characters, including new line characters, and can be of any length:
<?php
$key = "XXXXX";
$test = array($key => "test5");
for ($x = 0; $x < 500; $x++) {
$key .= "X";
$value = "test" . strlen($key);
$test[$key] = $value;
}
echo "<pre>";
print_r($test);
echo "</pre>";
?>
Keep in mind that using extremely long array indexes is not a good practice and could cost you lots of extra CPU time. However, if you have to use a long string as an array index you won't have to worry about the length or content.
30-Aug-2007 08:56
<?php
//EXAMPLE of Multi-Dimentional Array where as an array's keys are an array itself.
//It's so easy to create one like this.
$movie_to_watch = array ('Action'=>
array('Kanu Reeves' => 'Matrix Reloaded',
'Pearce Brosnan' => 'Die Another Day',
'Tom Cruz' => 'Mission Impossible',
'Jason Statham' => 'Crank',
'Danzel Washington' => 'Man on Fire'),
'Comedy' =>
array ('Charlie Chaplin' => 'City Lights',
'Jim Carrey' => 'Cable Guy',
'Rowan Atkinson' => 'The Ultimate Disaster'));
$type_wanted = 'Action'; //You may switch type from Action to Comedy.
$hero_wanted = 'Pearce Brosnan'; // You may switch hero from Pearce Brosnan to Jim Carrey.
print ("$hero_wanted 's $type_wanted movie is " . $movie_to_watch[$type_wanted][$hero_wanted].".");
// produces browser output as under:
// Pearce Brosnan 's Action movie is Die Another Day.
?>
21-Aug-2007 09:59
Hey..
here is a function which helps to avoid using empty/isset
checkings for arrays.
(it's acts simillar to 'default' modifier in Smarty)
Using this function you will avoid 'Undefined index' or
'Undefined offset' error.
<?php
$_POST['id']['other'] = 'val1';
/*
key exist (same as $_POST['id'][other])
*/
echo getRequestParam('id[other]', 'default value');
/*
key doesn't exist, we get default value (same as $_POST['var'])
*/
echo getRequestParam('var', 'default value');
function getRequestParam( $var, $default = '', $method = 'post' )
{
preg_match_all('!(\w+)!i',$var, $match );
array_shift($match);
$_vars = $match[0];
$ret = null;
if( strtoupper($method) == 'POST' ) {
$ret = _findRequestParam($_vars, $_POST);
}
elseif( strtoupper($method) == 'GET' ) {
$ret = _findRequestParam($_vars, $_GET);
}
elseif( strtoupper($method) == 'COOKIE' ) {
$ret = _findRequestParam($_vars, $_COOKIE);
}
elseif( strtoupper($method) == 'SESSION' ) {
$ret = _findRequestParam($_vars, $_SESSION);
}
if (! $ret )
return $default;
else
return $ret;
}
/**
@access private
*/
function _findRequestParam($vars, $find_in , $curr_key = 0)
{
static $ret;
if( array_key_exists($vars[$curr_key], $find_in) ) {
if( count( $vars)-1 == $curr_key ) {
$ret = $find_in[$vars[$curr_key]];
}
elseif( $curr_key < count( $vars)-1 ) {
_findRequestParam( $vars, $find_in[$vars[$curr_key]], $curr_key+1 );
}
}
return $ret;
}
?>
Hope this will help someone!
14-Jul-2007 03:34
Another note on unquoted array indices. Because it is first interpreted as a constant, it must obey the naming convention of constants. i.e. a letter or underscore followed by optional letter, digit and/or underscore characters.
Therefore while the following array declaration is legal:
$a = array('1st'=>'First','2nd'=>'Second');
Trying to access either array item as follows causes an error:
$first = "$a[1st]";
$second = "$a[2nd]";
11-Jul-2007 12:41
<b>Mark Gukov</b> wrote below:
Regarding the fact that there's no need to quote arrays keys when enclosed in double quotes: it only applies to single dimensional arrays.
The following works fine:
<?php
$r['a'] = 'apple';
echo "$r[a] is tasty.";
?>
...but in the case of multi-dimensional arrays:
<?php
$r['a']['b'] = 'banana';
echo "$r[a][b] is tasty.";
?>
would result in "Array[c] is tasty."
-----------------------------------------------------------------
However, the following runs fine;
$r['a']['b'] = 'banana';
echo "{$r[a][b]} is tasty.";
Just box it!
24-May-2007 12:37
It's slightly faster to use array_splice to remove an element of an array:
array_splice($array, $index, 1)
than to do it using the suggested method of unset and reindex:
unset($array[$index]);
$array = array_values($array);
The difference, however, is very small. With 950 iterations I had times of
unset and reindex: 0.22837495803833
splice: 0.22392416000366
20-Mar-2007 10:14
This Indonesian number speller function is twice
faster(*) than the one provided in class Terbilang by
anghuda(at)gmail(dot)com (25-May-2006 08:52):
http://www.lesantoso.com/terbilang.html
(*) 2.1 vs. 4.2 seconds in processing 10000 random numbers
16-Mar-2007 09:44
On array recursion...
Given the following code:
<?
$myarray = array('test',123);
$myarray[] = &$myarray;
print_r($myarray);
?>
The print_r() will display *RECURSION* when it gets to the third element of the array.
There doesn't appear to be any other way to scan an array for recursive references, so if you need to check for them, you'll have to use print_r() with its second parameter to capture the output and look for the word *RECURSION*.
It's not an elegant solution, but it's the only one I've found, so I hope it helps someone.
17-Jan-2007 01:55
About the automatic conversion of bare strings...
My opinion is that it never should have been implemented. Isn't it easier to NOT implement this "handy" feature in the first place? It is such a convenient way for "smart" programmers to write unsafe, not-futureproof code. Please remove this feature from future versions of PHP, please. (Hey, if you could change the OOP mechanisms between PHP 4 and PHP 5, why can't you make this change, right?)
This page should include details about how associative arrays are implemened inside PHP; e.g. using hash-maps or b-trees.
This has important implictions on the permance characteristics of associative arrays and how they should be used; e.g. b-tree are slow to insert but handle collisions better than hashmaps. Hashmaps are faster if there are no collisions, but are slower to retrieve when there are collisions. These factors have implictions on how associative arrays should be used.
27-Sep-2006 09:18
Regarding the fact that there's no need to quote arrays keys when enclosed in double quotes: it only applies to single dimensional arrays.
The following works fine:
<?php
$r['a'] = 'apple';
echo "$r[a] is tasty.";
?>
...but in the case of multi-dimensional arrays:
<?php
$r['a']['b'] = 'banana';
echo "$r[a][b] is tasty.";
?>
would result in "Array[c] is tasty."
21-Sep-2006 03:30
Regarding the message of phoenixbytes:
The line foreach($bad as $baddies); will just yield in $baddies the last value of the array $bad.
I think that wasn't your intention, in that case there are faster and better ways than foreach.
I think what you wanted to do is:
<?php
foreach($bad as $baddies) // make a collection
{
if (preg_match("/$baddies/i", $mailto)) // find a match
{
$addrmail = "false";
}
else
{
$addrmail = "true";
}
} // foreach end
?>
25-Jul-2006 11:28
in response to ch dot martin at gmail dot com
If you are using the following code:
<?php
$r = array('05' => "abc", '35' => "def");
foreach ($r as $key=>$value)
var_dump($key);
?>
and you need the array key '35' to be a string (for looping maybe), you can make sure the key is a string by appending a 0 on the front.
'035' instead of '35'
09-Jun-2006 06:40
Extremely irritating quirk regarding the variable types of array keys:
<?php
$r = array('05' => "abc", '35' => "def");
foreach ($r as $key=>$value)
var_dump($key);
?>
The first var_dump for '05' is:
string(2) "05"
as expected. But the second, '35', turns out as:
int(35)
Php apparently decided to make the 35 became an int, but not the 05 (presumably because it leads with a zero). As far as I can see, there is absolutely no way of making string(2) "35" an array key.
25-May-2006 01:52
this is simpler tha function display_angka_bilangan by ktaufik(at)gmail(dot)com (16-Feb-2005 12:40)
<?
/*
*
* Class : Terbilang
* Spell quantity numbers in Indonesian or Malay Language
*
*
* author: huda m elmatsani
* 21 September 2004
* freeware
*
* example:
* $bilangan = new Terbilang;
* echo $bilangan -> eja(137);
* result: seratus tiga puluh tujuh
*
*
*/
Class Terbilang {
function terbilang() {
$this->dasar = array(1=>'satu','dua','tiga','empat','lima','enam',
'tujuh','delapan','sembilan');
$this->angka = array(1000000000,1000000,1000,100,10,1);
$this->satuan = array('milyar','juta','ribu','ratus','puluh','');
}
function eja($n) {
$i=0;
while($n!=0){
$count = (int)($n/$this->angka[$i]);
if($count>=10) $str .= $this->eja($count). " ".$this->satuan[$i]." ";
else if($count > 0 && $count < 10)
$str .= $this->dasar[$count] . " ".$this->satuan[$i]." ";
$n -= $this->angka[$i] * $count;
$i++;
}
$str = preg_replace("/satu puluh (\w+)/i","\\1 belas",$str);
$str = preg_replace("/satu (ribu|ratus|puluh|belas)/i","se\\1",$str);
return $str;
}
}
?>
09-May-2006 08:46
phoenixbytes: The regex you have posted for matching email addresses is incorrect. Among other things, it does not allow '+' before the '@' (which is perfectly valid and can be quite useful to separate extensions of a single address). RFC 822 [1] defines the grammar for valid email addresses, and (the extemely long) regex implementing can be found at [2]. Even the "Add Note" page here at php.net says:
[quote]
And if you're posting an example of validating email addresses, please don't bother. Your example is almost certainly wrong for some small subset of cases. See this information from O'Reilly Mastering Regular Expressions book for the gory details.
[/quote]
A note to others: please do your homework before writing another email-matching regex.
[1] http://www.ietf.org/rfc/rfc0822.txt?number=822
[2] http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html.
17-Apr-2006 12:10
i use the array() function for deciding upon an email address's validity, i have a 'wap stalker' of my site that loves to exploit every hole i leave, so i used the following script to avoid being email bombed with my own file sender script, the array() is used to filter out undesirable email providers and, of course, any and all of my own addresses. before all that i used a REGEX to make sure it's an actual email address before going any further.
$mailto = "mail.domain.org"; // the input to be tested
if (preg_match("/^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,6}$/i", $mailto)) // see if it's really an email address
{
$bad = array('mytrashmail.com', 'mymail.ro', 'acasa.ro', 'gala.net', 'phoenixbytes'); // pick out the victims
foreach($bad as $baddies); // make a collection
if (preg_match("/$baddies/i", $mailto)) // find a match
{
$addrmail = "false";
}
else
{
$addrmail = "true";
}
}
else
{
$addrmail = "false";
}
$addrmail can then be used in an argument.
$baddies can be used to give a list, if necessary.
i hope this helps someone.
01-Apr-2006 08:54
Passing variables into the array constructor:
Just a NOOB pointer, I couldn't find other examples for this. If you want to pass the value of an existing variable into the array() constructor, you can quote it or not, both methods are valid.
<?
$foo_value = 'foo string';
$bar_value = 'bar string';
$myArray = array(
'foo_key' => $foo_value, // not quoted
'bar_key' => "$bar_value"); // quoted
foreach ($myArray as $k => $v) {
echo "\$myArray[$k] => $v.<br />\n";
}
?>
Both of these will work as expected, but the unqoted $foo_value method above is marginally faster because adding quotes adds an additional string de-reference.
13-Dec-2005 05:41
if you need to check a multidimensonal array for values it's handy to store it like
$ar['key1'][0]
$ar['key2'][0]
$ar['key3'][0]
$ar['key1'][1]
$ar['key2'][1]
$ar['key3'][1]
and to loop the keys.
Fill the array (from a database-request):
while($rf=mysql_fetch_row($rs))
{
$nr=$rf[0];
$channel['nr'][$nr]=$rf[1];
$channel['chatter'][$nr]=$rf[2];
}
Call the values:
foreach(array_keys($channel['nr']) as $test)
{
print ' nr:'.$test.'<br>';
print 'value nr: '.$channel['nr'][$test].'<br>';
print ' chatter: '.$channel['chatter'][$test].'<br>';
}
This is useful, if you have to look later for an element
inside the array:
if(in_array($new_value,$channel['nr'])) print 'do something.';
Hope this helps someone.
30-Sep-2005 09:55
Regarding the previous comment, beware of the fact that reference to the last value of the array remains stored in $value after the foreach:
<?php
foreach ( $arr as $key => &$value )
{
$value = 1;
}
// without next line you can get bad results...
//unset( $value );
$value = 159;
?>
Now the last element of $arr has the value of '159'. If we remove the comment in the unset() line, everything works as expected ($arr has all values of '1').
Bad results can also appear in nested foreach loops (the same reason as above).
So either unset $value after each foreach or better use the longer form:
<?php
foreach ( $arr as $key => $value )
{
$arr[ $key ] = 1;
}
?>
27-Sep-2005 08:53
Regarding the previous comment, thw following code does the job:
<?php
foreach($arr as $key => &$value) {
$value = 1;
}
?>
19-Sep-2005 01:14
Regarding the previous comment, the fact that this code has no effect is perfectly expected:
<?php
foreach($arr as $value) {
$value = 1;
}
?>
The reason that this doesn't work, is because each time that PHP goes through the loop, it _copies_ the value of the array element into $value. So if you assign a new value to the data in $value, it has no effect on the actual array, because you only changed the value of the copy that was put in $value.
As was discovered in the previous post, the only way to get around this problem is to change the value in the original array. Hence, a typical foreach should instead look like this:
<?php
foreach($arr as $key => $value) {
$arr[$key] = 1;
}
?>
28-Aug-2005 09:28
[Editor's note: You can achieve what you're looking for by referencing $single, rather than copying it by value in your foreach statement. See http://php.net/foreach for more details.]
Don't know if this is known or not, but it did eat some of my time and maybe it won't eat your time now...
I tried to add something to a multidimensional array, but that didn't work at first, look at the code below to see what I mean:
<?php
$a1 = array( "a" => 0, "b" => 1 );
$a2 = array( "aa" => 00, "bb" => 11 );
$together = array( $a1, $a2 );
foreach( $together as $single ) {
$single[ "c" ] = 3 ;
}
print_r( $together );
/* nothing changed result is:
Array
(
[0] => Array
(
[a] => 0
[b] => 1
)
[1] => Array
(
[aa] => 0
[bb] => 11
)
) */
foreach( $together as $key => $value ) {
$together[$key]["c"] = 3 ;
}
print_r( $together );
/* now it works, this prints
Array
(
[0] => Array
(
[a] => 0
[b] => 1
[c] => 3
)
[1] => Array
(
[aa] => 0
[bb] => 11
[c] => 3
)
)
*/
?>
04-Aug-2005 06:24
It is a kind of simple muti-dimensional array list.
I have made it just to give a simple idea.
<?php
echo "Here we'll see how to create a multi-dimensional array.\n";
$a=array('fruits'=>array('a'=>'orange',
'b'=>'grape',c=>'apple'),
'numbers'=>array(1,2,3,4,5,6),
'holes'=>array('first',5=>'second',
'third')
);
foreach($a as $list=>$things){
foreach($things as $newlist=>$counter){
echo $counter;
}
}
?>
22-Apr-2005 07:10
Here's a simple function to insert a value into some position in an array
<?php
function array_insert($array,$pos,$val)
{
$array2 = array_splice($array,$pos);
$array[] = $val;
$array = array_merge($array,$array2);
return $array;
}
?>
and now for example...
<?php
$a = array("John","Paul","Peter");
$a = array_insert($a,1,"Mike");
?>
Now $a will be "John","Mike","Paul","Peter"
21-Apr-2005 04:16
Beware that if you're using strings as indices in the $_POST array, that periods are transformed into underscores:
<html>
<body>
<?php
printf("POST: "); print_r($_POST); printf("<br/>");
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="Windows3.1" value="Sux">
<input type="submit" value="Click" />
</form>
</body>
</html>
Once you click on the button, the page displays the following:
POST: Array ( [Windows3_1] => Sux )
05-Apr-2005 03:24
Something that tripped me up:
If you mix string and integer keys, be careful if you are doing a comparison on the to find if a string key exists.
For example, this will not do what you expect it to do:
<?php
$exampleArray = array();
$exampleArray['foo'] = 'bar';
$exampleArray[] = 'Will create 0 index';
$keyWeAreLookingFor = "correctKey";
foreach ($exampleArray as $key => $value){
if ($key == $keyWeAreLookingFor){
print "Found Key";
}
}
?>
It will print "Found Key", because (I presume) when PHP makes the comparison between the string "correctKey" and the index 0, it casts the string to an integer, rather than casting 0 to the string "0" and then doing the comparison.
Using === fixes the problem:
<?php
foreach ($exampleArray as $key => $value){
if ($key === $keyWeAreLookingFor){
print "Found Key";
}
}
?>
28-Mar-2005 04:40
Used to creating arrays like this in Perl?
@array = ("All", "A".."Z");
Looks like we need the range() function in PHP:
<?php
$array = array_merge(array('All'), range('A', 'Z'));
?>
You don't need to array_merge if it's just one range:
<?php
$array = range('A', 'Z');
?>
16-Feb-2005 08:59
On array copying a deep copy is done of elements except those elements which are references, in which case the reference is maintained. This is a very important thing to understand if you intend on mixing references and recursive arrays.
By Example:
$a = array( 1 );
$aref_a = array( &$a );
$copy_aref_a = $aref_a;
$acopy_a = array( $a );
$copy_acopy_a = $acopy_a;
$a[] = 5;
$acopy_a[0][] = 6;
print_r( $aref_a ); //Shows: ( (1,5) )
print_r( $copy_aref_a ); //Shows: ( (1,5) )
print_r( $acopy_a ); //Shows: ( (1, 6) )
print_r( $copy_acopy_a ); //Shows: ( (1) )
16-Feb-2005 08:40
For you who works for localized "say" number to letter ( ex , 7=> seven, 8=>eight) for Bahasa Indonesia.
Indonesia "say" or "Terbilang" is based on 3 digit number.
thousands, millions and trillions .... will be based on the 3 digit number.
In Indonesia you say 137 as "Seratus Tiga Puluh Tujuh"
<?php
//build random 3 digit number to be "said" in Bahasa Indonesia
$x=rand(0,9);
$y=rand(0,9);
$z=rand(0,9);
function display_angka_bilangan($n) {
$angka = array(
1 => 'satu',
2 => 'dua',
3 => 'tiga',
4 => 'empat',
5 => "lima",
6 => 'enam',
7 => 'tujuh',
8 => 'delapan',
9 => 'sembilan'
);
return $angka[$n];
}
// Terbilang X-------Say X
if ($x==1){$terbilangx="seratus ";}
elseif ($x==0){$terbilangx='';}
else {$terbilangx=''.display_angka_bilangan($x).' '.'ratus ';}
// Terbilang Y ------Say Y
if ($y==0){$terbilangy='';}
elseif ($y==1 && $z==1){$terbilangy="sebelas";$terbilangz='';}
elseif ($y==1 && $z==0){$terbilangy="sepuluh ";$terbilangz='';}
elseif ($y==1 && $z!==1 && $z!==0){$terbilangy=''.display_angka_bilangan($z).' belas ';}
else {$terbilangy=''.display_angka_bilangan($y).' '.'puluh ';}
// Terbilang z ------Say z
if ($z==0){$terbilangz="";}
elseif ($z==0 && $y==1){$terbilangz="";}
elseif ($z==1 && $y==1){$terbilangz="";}
elseif($y==0) {$terbilangz="".display_angka_bilangan($z);}
elseif ($y==1 && $z!==1 && $z!==0) {$terbilangz="";}
else {$terbilangz="".display_angka_bilangan($z);};
$terbilang=$terbilangx.$terbilangy.$terbilangz;
echo $x.$y.$z." ";
echo $terbilang;
?>
Hope it is useful
ktaufik(at)gmail(dot)com
05-Jan-2005 03:06
[Editor's Note: (Second example.) These are not "arrays in arrays". These are single-dimensional arrays containing stdClass objects; all objects are referenced by default in PHP5. You can see in the var_dump output that they point to the same object.]
Attention with Arrays in Arrays!
If you copy (=) an array which contains arrays it will be REFERENCED not COPIED.
Example:
<?php
/* GOOD ONE */
echo "<b>Here copy (=) works correct:</b><br>";
/* Initialise Array 1 */
$x1 = array(array(10,20),array(30,40));
/* COPY Array */
$x2 = $x1;
/* Change some values in Array 2 */
$x2[0][0]=77;
$x2[1][1]=99;
echo "<b>Original:</b><pre>";
var_dump($x1);
echo "</pre><b>Changed Copy:</b><pre>";
var_dump($x2);
/* BAAAAAAAD ONE */
echo "</pre><hr><b>Here copy (=) FAILS:</b><br>";
/* Initialise Array 1 */
$a1[0]->bla[0]->id=10;
$a1[0]->bla[1]->id=20;
$a1[1]->bla[0]->id=30;
$a1[1]->bla[1]->id=40;
/* COPY Array */
$a2 = $a1;
/* Change some values in Array 2 (!) */
$a2[0]->bla[0]->id=77;
$a2[1]->bla[1]->id=99;
echo "<b>Original:</b><pre>";
var_dump($a1);
echo "</pre><b>Changed Copy:</b><pre>";
var_dump($a2);
echo "</pre>";
php?>
The output of $a1 and $a2 will be the same..
08-Nov-2004 09:26
Programmers new to PHP may find the following surprising:
<?php
$x[1] = 'foo';
$x[0] = 'bar';
echo "Original array:\n";
var_dump($x);
array_pop($x);
echo "Array after popping last element:\n";
var_dump($x);
?>
The surprise is that element 0 is deleted, not element 1. Apparently the notion of "last element" has more to do with how the array is stored internally than with which element has the highest numeric index. I recently translated a Perl program to PHP and was bitten by this one.
My solution was to identify all the places in my code where I could prove that the array elements were assigned sequentially. In those cases it is safe to use array_pop, array_splice, etc. since the array indices correspond with the array layout. For the other cases, my solution was to write replacements for the built-in array functions such as this one:
<?php
function safe_pop(&$a)
{
if (!isset($a))
return;
if (!is_array($a))
return;
if (count($a) == 0)
return;
unset($a[max(array_keys($a))]);
}
?>
19-Nov-2003 04:51
Negative and positive array indices have different behavior when it comes to string<->int conversion. 1 and "1" are treated as identical indices, -1 and "-1" are not. So:
$arr["1"] and $arr[1] refer to the same element.
$arr["-1"] and $arr[-1] refer to different elements.
The following code:
<?
$arr[1] = "blue";
$arr["1"] = "red";
$arr[-1] = "blue";
$arr["-1"] = "red";
var_dump($arr);
?>
produces the output:
array(3) {
[1]=>
string(3) "red"
[-1]=>
string(4) "blue"
["-1"]=>
string(3) "red"
}
This code should create an array with either two or four elements. Which one should be the "correct" behavior is an exercise left to the reader....
16-Jul-2003 11:22
It is quite simple, but don't forget when you'll using foreach with forms arrays.
If your field name is:
<input type="checkbox" name="foo['bar'][]" ...
It doesn't work.
This should work:
<input type="checkbox" name="foo[bar][]" ...
11-Jul-2003 11:59
I was having trouble getting javascript arrays and php arrays to work together with a Check All checkboxe. Here is a simple solution. Clicking the 'Check All' checkbox will check all checkboxes on the form.
<script language="JavaScript">
function chkAll(frm, arr, mark) {
for (i = 0; i <= frm.elements.length; i++) {
try{
if(frm.elements[i].name == arr) {
frm.elements[i].checked = mark;
}
} catch(er) {}
}
}
</script>
<form name='foo'>
<input type="checkbox" name="ca" value="1" onClick="chkAll(this.form, 'formVar[chkValue][]', this.checked)">
<?php
for($i = 0; $i < 5; $i++){
echo("<input type='checkbox' name='formVar[chkValue][]' value='$i'>");
}
?>
</form>
Dean M.
26-Mar-2003 06:13
I didn't find this anywhere in the docs and i think it is worth a mention:
$a[] = &$a;
print_r($a);
// will output:
/*
Array
(
[0] => Array
*RECURSION*
)
*/
// this means that $a[0] is a reference to $a ( that is detected by print_r() ). I guess this is what the manual calls 'recursive arrays'.
"Using NULL as a key will evaluate to an empty string. Using an emptry string as key will create (or overwrite) a key with an empty string and its value, it is not the same as using empty brackets."
If you create an array like this:
$foo = array(null => 'bar');
And then want to access 'bar', you must use this syntax:
echo $foo['']; // notice the two single quotes
This will of course cause a fatal error:
echo $foo[];
29-Nov-2002 11:10
Dereferencing arrays takes some time, but is not terribly expensive.
I wrote two dummy loops to test performance:
for ($i =0; $i < count($a); $i++) {
$x = $a[$b[$i]];
$y = $a[$b[$i]];
$z = $a[$b[$i]];
}
for ($i =0; $i < count($a); $i++) {
$q = $b[$i];
$x = $a[$q];
$y = $a[$q];
$z = $a[$q];
}
The first loop is 6.5% slower than the second. Meaning that dereferencing arrays is not terribly expensive, unless you do it a whole lot. I would expect that each extra reference costs about 3% in speed. The lesson is that if you're going to be using a specific value in an array for a number of operations, you can gain a little speed by assigning it to a temp variable (or creating a reference with $q = &$b[$i]) but it's not worth getting crazy over.
I tested this with iterations of 10,000 and 100,000 on php 4.2 and the results were consistent.
15-Oct-2002 06:50
Recursive arrays and multi-dimensional arrays are the same thing and completely identical.
The following confirms this:
$fruits1["european"]["green"] = "Apple";
$fruits2 = array ( "european" => array ( "green" => "Apple"));
print ($fruits1 === $fruits2);
Result: 1 (= true)
11-Jun-2002 12:40
Arrays can be merged using + as discussed in the notes for array_merge.
http://www.php.net/manual/en/function.array-merge.php
25-May-2002 01:06
For all of you having problems when using php arrays in an HTML form input field name, and wanting to validate the form using javascript for example, it is much easier to specify an id for the field as well, and use this id for validation.
Example:
<input type="text" id="lastname" name="fields[lastname]">
then in the javascript check:
if(formname.lastname.value == "") {
alert("please enter a lastname!");
}
This works very well. If you have any problems with it, let me know.
