数组

PHP 中的数组实际上是一个有序图。图是一种把 values 映射到 keys 的类型。此类型在很多方面做了优化,因此可以把它当成真正的数组来使用,或列表(矢量),散列表(是图的一种实现),字典,集合,栈,队列以及更多可能性。因为可以用另一个 PHP 数组作为值,也可以很容易地模拟树。

解释这些结构超出了本手册的范围,但对于每种结构至少会发现一个例子。要得到这些结构的更多信息,建议参考有关此广阔主题的外部著作。

语法

定义 array()

可以用 array() 语言结构来新建一个 array。它接受一定数量用逗号分隔的 key => value 参数对。

array( [key =>]
value
     , ...
     )
// key 可以是 integer 或者 string
// value 可以是任何值

<?php
$arr
= array("foo" => "bar", 12 => true);

echo
$arr["foo"]; // bar
echo $arr[12];    // 1
?>

key 可以是 integer 或者 string。如果键名是一个 integer 的标准表达方法,则被解释为整数(例如 "8" 将被解释为 8,而 "08" 将被解释为 "08")。key 中的浮点数被取整为 integer。PHP 中没有不同的数字下标和关联下标数组,数组的类型只有一种,它可以同时包含整型和字符串型的下标。

值可以是任何值。

<?php
$arr
= array("somearray" => array(6 => 5, 13 => 9, "a" => 42));

echo
$arr["somearray"][6];    // 5
echo $arr["somearray"][13];   // 9
echo $arr["somearray"]["a"];  // 42
?>

如果对给出的值没有指定键名,则取当前最大的整数索引值,而新的键名将是该值加一。如果指定的键名已经有了值,则该值会被覆盖。

<?php
// This array is the same as ...
array(5 => 43, 32, 56, "b" => 12);

// ...this array
array(5 => 43, 6 => 32, 7 => 56, "b" => 12);
?>

警告

自 PHP 4.3.0 起,上述的索引生成方法改变了。如今如果给一个当前最大键名是负值的数组添加一个新值,则新生成的的索引将为零(0)。以前新生成的索引为当前最大索引加一,和正值的索引相同。

使用 TRUE 作为键名将使 integer 1 成为键名。使用 FALSE 作为键名将使 integer 0 成为键名。使用 NULL 作为键名将等同于使用空字符串。使用空字符串作为键名将新建(或覆盖)一个用空字符串作为键名的值,这和用空的方括号不一样。

不能用数组和对象作为键名。这样做会导致一个警告:Illegal offset type

用方括号的语法新建/修改

可以通过明示地设定值来改变一个现有的数组。

这是通过在方括号内指定键名来给数组赋值实现的。也可以省略键名,在这种情况下给变量名加上一对空的方括号(“[]”)。
$arr[key] = value;
$arr[] = value;
// key 可以是 integer 或者 string
// value 可以为任何值。
如果 $arr 还不存在,将会新建一个。这也是一种定义数组的替换方法。要改变一个值,只要给它赋一个新值。如果要删除一个键名/值对,要对它用 unset()

<?php
$arr
= array(5 => 1, 12 => 2);
$arr[] = 56;    // This is the same as $arr[13] = 56;
                // at this point of the script
$arr["x"] = 42; // This adds a new element to
                // the array with key "x"
unset($arr[5]); // This removes the element from the array
unset($arr);    // This deletes the whole array
?>

注: 如上所述,如果给出方括号但没有指定键名,则取当前最大整数索引值,新的键名将是该值 + 1。如果当前还没有整数索引,则键名将为 0。如果指定的键名已经有值了,该值将被覆盖。

警告

自 PHP 4.3.0 起,上述的索引生成方法改变了。如今如果给一个当前最大键名是负值的数组添加一个新值,则新生成的的索引将为零(0)。以前新生成的索引为当前最大索引加一,和正值的索引相同。

注意这里所使用的最大整数键名不一定当前就在数组中。它只要在上次数组重新生成索引后曾经存在过就行了。以下面的例子来说明:

<?php
// 创建一个简单的数组
$array = array(1, 2, 3, 4, 5);
print_r($array);

// 现在删除其中的所有单元,但保持数组本身的结构
foreach ($array as $i => $value) {
    unset(
$array[$i]);
}
print_r($array);

// 添加一个单元(注意新的键名是 5,而不是你可能以为的 0)
$array[] = 6;
print_r($array);

// 重新索引:
$array = array_values($array);
$array[] = 7;
print_r($array);
?>

上例将输出:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
Array
(
)
Array
(
    [5] => 6
)
Array
(
    [0] => 6
    [1] => 7
)

实用函数

有相当多的实用函数作用于数组,参见数组函数一节。

注: unset() 函数允许取消一个数组中的键名。要注意数组将不会重建索引。

<?PHP
$a
= array( 1 => 'one', 2 => 'two', 3 => 'three' );
unset(
$a[2] );
/* 将产生一个数组,定义为
   $a = array( 1=>'one', 3=>'three');
   而不是
   $a = array( 1 => 'one', 2 => 'three');
*/
$b = array_values($a);
// Now $b is array(0 => 'one', 1 =>'three')
?>

foreach 控制结构是专门用于数组的。它提供了一个简单的方法来遍历数组。

数组做什么和不做什么

为什么 $foo[bar] 错了?

应该始终在用字符串表示的数组索引上加上引号。例如用 $foo['bar'] 而不是 $foo[bar]。但是为什么 $foo[bar] 错了呢?可能在老的脚本中见过如下语法:

<?php
$foo
[bar] = 'enemy';
echo
$foo[bar];
// etc
?>

这样是错的,但可以正常运行。那么为什么错了呢?原因是此代码中有一个未定义的常量(bar)而不是字符串('bar'-注意引号),而 PHP 可能会在以后定义此常量,不幸的是你的代码中有同样的名字。它能运行,是因为 PHP 自动将裸字符串(没有引号的字符串且不对应于任何已知符号)转换成一个其值为该裸字符串的正常字符串。例如,如果没有常量定义为 bar,PHP 将把它替代为 'bar' 并使用之。

注: 这并不意味着总是给键名加上引号。用不着给键名为常量变量的加上引号,否则会使 PHP 不能解析它们。

<?php
error_reporting
(E_ALL);
ini_set('display_errors', true);
ini_set('html_errors', false);
// Simple array:
$array = array(1, 2);
$count = count($array);
for (
$i = 0; $i < $count; $i++) {
    echo
"\nChecking $i: \n";
    echo
"Bad: " . $array['$i'] . "\n";
    echo
"Good: " . $array[$i] . "\n";
    echo
"Bad: {$array['$i']}\n";
    echo
"Good: {$array[$i]}\n";
}
?>

注: 上例将输出:

Checking 0:
Notice: Undefined index:  $i in /path/to/script.html on line 9
Bad:
Good: 1
Notice: Undefined index:  $i in /path/to/script.html on line 11
Bad:
Good: 1

Checking 1:
Notice: Undefined index:  $i in /path/to/script.html on line 9
Bad:
Good: 2
Notice: Undefined index:  $i in /path/to/script.html on line 11
Bad:
Good: 2

演示此效应的更多例子:

<?php
// 显示所有错误
error_reporting(E_ALL);

$arr = array('fruit' => 'apple', 'veggie' => 'carrot');

// 正确
print $arr['fruit'];  // apple
print $arr['veggie']; // carrot

// 不正确。This works but also throws a PHP error of
// level E_NOTICE because of an undefined constant named fruit
//
// Notice: Use of undefined constant fruit - assumed 'fruit' in...
print $arr[fruit];    // apple

// Let's define a constant to demonstrate what's going on.  We
// will assign value 'veggie' to a constant named fruit.
define('fruit','veggie');

// Notice the difference now
print $arr['fruit'];  // apple
print $arr[fruit];    // carrot

// The following is okay as it's inside a string.  Constants are not
// looked for within strings so no E_NOTICE error here
print "Hello $arr[fruit]";      // Hello apple

// With one exception, braces surrounding arrays within strings
// allows constants to be looked for
print "Hello {$arr[fruit]}";    // Hello carrot
print "Hello {$arr['fruit']}";  // Hello apple

// This will not work, results in a parse error such as:
// Parse error: parse error, expecting T_STRING' or T_VARIABLE' or T_NUM_STRING'
// This of course applies to using autoglobals in strings as well
print "Hello $arr['fruit']";
print
"Hello $_GET['foo']";

// Concatenation is another option
print "Hello " . $arr['fruit']; // Hello apple
?>

当打开 error_reporting() 来显示 E_NOTICE 级别的错误(例如将其设为 E_ALL)时将看到这些错误。默认情况下 error_reporting 被关闭不显示这些。

和在语法一节中规定的一样,在方括号(“[”和“]”)之间必须有一个表达式。这意味着可以这样写:

<?php
echo $arr[somefunc($bar)];
?>

这是一个用函数返回值作为数组索引的例子。PHP 也可以用已知常量,可能之前已经见过 E_*

<?php
$error_descriptions
[E_ERROR]   = "A fatal error has occured";
$error_descriptions[E_WARNING] = "PHP issued a warning";
$error_descriptions[E_NOTICE]  = "This is just an informal notice";
?>

注意 E_ERROR 也是个合法的标识符,就和第一个例子中的 bar 一样。但是上一个例子实际上和如下写法是一样的:

<?php
$error_descriptions
[1] = "A fatal error has occured";
$error_descriptions[2] = "PHP issued a warning";
$error_descriptions[8] = "This is just an informal notice";
?>

因为 E_ERROR 等于 1,等等。

如同在以上例子中解释的那样,$foo[bar] 起作用但其实是错误的。它起作用是因为根据语法的预期,bar 被当成了一个常量表达式。然而,在这个例子中不存在名为 bar 的常量。PHP 就假定指的是字面上的 bar,也就是字符串 "bar",但忘记加引号了。

那么为什么这样做不好?

在未来的某一时刻,PHP 开发小组可能会想新增一个常量或者关键字,或者用户可能希望以后在自己的程序中引入新的常量,那就有麻烦了。例如已经不能这样用 emptydefault 这两个词了,因为他们是保留字

注: 重申一次,在双引号字符串中,不给索引加上引号是合法的因此 "$foo[bar]"是合法的。至于为什么参见以上的例子和字符串中的变量解析中的解释。

转换为数组

对于任何的类型:整型、浮点、字符串、布尔和资源,如果将一个值转换为数组,将得到一个仅有一个元素的数组(其下标为 0),该元素即为此标量的值。

如果将一个对象转换成一个数组,所得到的数组的元素为该对象的属性(成员变量),其键名为成员变量名。

如果将一个 NULL 值转换成数组,将得到一个空数组。

比较

有可能通过 array_diff()数组运算符来比较数组。

例子

PHP 中的数组类型有非常多的用途,因此这里有一些例子展示数组的完整威力。

<?php
// this
$a = array( 'color' => 'red',
            
'taste' => 'sweet',
            
'shape' => 'round',
            
'name'  => 'apple',
                       
4        // key will be 0
          
);

// is completely equivalent with
$a['color'] = 'red';
$a['taste'] = 'sweet';
$a['shape'] = 'round';
$a['name']  = 'apple';
$a[]        = 4;        // key will be 0

$b[] = 'a';
$b[] = 'b';
$b[] = 'c';
// will result in the array array(0 => 'a' , 1 => 'b' , 2 => 'c'),
// or simply array('a', 'b', 'c')
?>

例子 11-6. 使用 array()

<?php
// Array as (property-)map
$map = array( 'version'    => 4,
              
'OS'         => 'Linux',
              
'lang'       => 'english',
              
'short_tags' => true
            
);

// strictly numerical keys
$array = array( 7,
                
8,
                
0,
                
156,
                -
10
              
);
// this is the same as array(0 => 7, 1 => 8, ...)

$switching = array(         10, // key = 0
                    
5    =>  6,
                    
3    =>  7,
                    
'a'  =>  4,
                            
11, // key = 6 (maximum of integer-indices was 5)
                    
'8'  =>  2, // key = 8 (integer!)
                    
'02' => 77, // key = '02'
                    
0    => 12  // the value 10 will be overwritten by 12
                  
);
// empty array
$empty = array();
?>

例子 11-7. 集合

<?php
$colors
= array('red', 'blue', 'green', 'yellow');

foreach (
$colors as $color) {
    echo
"Do you like $color?\n";
}

?>

上例将输出:

Do you like red?
Do you like blue?
Do you like green?
Do you like yellow?

直接改变数组的值在 PHP 5 中可以通过引用传递来做到。之前的版本需要需要采取别的方法:

例子 11-8. 集合

<?php
// PHP 5
foreach ($colors as &$color) {
    
$color = strtoupper($color);
}
unset(
$color); /* 确保下面对 $color 的覆盖不会影响到前一个数组单元 */
// 之前版本的方法
foreach ($colors as $key => $color) {
    
$colors[$key] = strtoupper($color);
}

print_r($colors);
?>

上例将输出:

Array
(
    [0] => RED
    [1] => BLUE
    [2] => GREEN
    [3] => YELLOW
)

本例产生一个基于一的数组。

例子 11-9. 基于一的数组

<?php
$firstquarter  
= array(1 => 'January', 'February', 'March');
print_r($firstquarter);
?>

上例将输出:

Array
(
    [1] => 'January'
    [2] => 'February'
    [3] => 'March'
)
*/
?>

例子 11-10. 填充数组

<?php
// fill an array with all items from a directory
$handle = opendir('.');
while (
false !== ($file = readdir($handle))) {
    
$files[] = $file;
}
closedir($handle);
?>

数组是有序的。也可以使用不同的排序函数来改变顺序。更多信息参见数组函数。可以用 count() 函数来数出数组中元素的个数。

例子 11-11. 数组排序

<?php
sort
($files);
print_r($files);
?>

因为数组中的值可以为任意值,也可是另一个数组。这样可以产生递归或多维数组。

例子 11-12. 递归和多维数组

<?php
$fruits
= array ( "fruits"  => array ( "a" => "orange",
                                       
"b" => "banana",
                                       
"c" => "apple"
                                     
),
                  
"numbers" => array ( 1,
                                       
2,
                                       
3,
                                       
4,
                                       
5,
                                       
6
                                     
),
                  
"holes"   => array (      "first",
                                       
5 => "second",
                                            
"third"
                                     
)
                );

// Some examples to address values in the array above
echo $fruits["holes"][5];    // prints "second"
echo $fruits["fruits"]["a"]; // prints "orange"
unset($fruits["holes"][0]);  // remove "first"

// Create a new multi-dimensional array
$juices["apple"]["green"] = "good";
?>

需要注意数组的赋值总是会涉及到值的拷贝。需要在复制数组时用引用符号(&)。

<?php
$arr1
= array(2, 3);
$arr2 = $arr1;
$arr2[] = 4; // $arr2 is changed,
             // $arr1 is still array(2,3)

$arr3 = &$arr1;
$arr3[] = 4; // now $arr1 and $arr3 are the same
?>


add a note add a note User Contributed Notes
26-Oct-2006 12:18
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.
Mark Gukov
28-Sep-2006 05: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."
petruzanautico at yahoo dot com dot ar
21-Sep-2006 11: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
?>
php dot net at todandlorna dot com
26-Jul-2006 07: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'
ch dot martin at gmail dot com
09-Jun-2006 02: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.
anghuda(at)gmail(dot)com
25-May-2006 09: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;
   }
}

?>
benjcarson at digitaljunkies dot ca
10-May-2006 04: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.
phoenixbytes at o2 dot co dot uk
17-Apr-2006 08: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.
crozzer
02-Apr-2006 04: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.
sales at maboom dot ch
14-Dec-2005 01: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.
ia [AT] zoznam [DOT] sk
30-Sep-2005 05: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;
}
?>
stochnagara at hotmail dot com
27-Sep-2005 04:53
Regarding the previous comment, thw following code does the job:

<?php
foreach($arr as $key => &$value) {
  
$value = 1;
}
?>
jazepstein OverAt GeeMail dot com
19-Sep-2005 09: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;
}
?>
caifara aaaat im dooaat be
28-Aug-2005 05: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
       )
)
*/

?>
uzakufuklar at hotmail dot com
04-Aug-2005 02: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;
   }
}
?>
t0russ a t g m a i l d o t c o m
23-Jun-2005 01:27
re: jeff splat codedread splot com
when posting spaces are also translated into underscores,
quotes are translated into \" and \'
so <input name="Bill Gay'ts" value="micro$oft blows"> will be named as $_POST['Bill_Gay\'ts']
z
22-Apr-2005 03: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"
jeff splat codedread splot com
22-Apr-2005 12: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 )
roland dot swingler at transversal dot com
05-Apr-2005 11: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";
  }
}
?>
lars-phpcomments at ukmix dot net
29-Mar-2005 12: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');
?>
mortoray at ecircle-ag dot com
16-Feb-2005 04: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) )
ktaufik(at)gmail(dot)com
16-Feb-2005 04: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
db
05-Jan-2005 11: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..
Guillaume Beaulieu
31-Dec-2004 02:53
There is no warning nor error if you make something like:

foreach($a as $b => $b) {
   print $b;
}

It is somewhat weird, but in the philosophy of "permit everything" of php.
Joe Morrison <jdm at powerframe dot com>
08-Nov-2004 05: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))]);
}

?>
Cameron Brown
19-Nov-2003 12: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....
akamai at veloxmail dot com dot br
17-Jul-2003 07: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][]" ...
agape_logos at shaw dot ca
12-Jul-2003 07: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.
chroniton .at. gmx .dot. li
27-Mar-2003 02: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'.
07-Mar-2003 07:28
"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[];
wmoranATpotentialtechDOTcom
30-Nov-2002 07: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.
mu at despammed dot com
15-Oct-2002 02: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)
hramrach_L at centrum. cz ;-)
11-Jun-2002 08:40
Arrays can be merged using + as discussed in the notes for array_merge.
 http://www.php.net/manual/en/function.array-merge.php
philip at boone dot at
25-May-2002 09: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.
mjp at pilcrow dot madison dot wi dot us
22-Feb-2000 06:18
Those with a perl background may be surprised to learn that the 'thick arrow' and comma operators are not synonymous in array construction.

For example, the following are equivalent:

$ary = array("foo" => "bar", 1, 2);
$ary = array("foo" => "bar", 0 => 1, 1 => 2);