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

search for in the

Objects> <Strings
Last updated: Fri, 02 Jan 2009

view this page in

Arrays

An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.

Explanation of those data structures is beyond the scope of this manual, but at least one example is provided for each of them. For more information, look towards the considerable literature that exists about this broad topic.

Syntax

Specifying with array()

An array can be created by the array() language construct. It takes as parameters any number of comma-separated key => value pairs.

array(  key =>  value
     , ...
     )
// key may only be an integer or string
// value may be any value of any type
<?php
$arr 
= array("foo" => "bar"12 => true);

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

A key may be either an integer or a string. If a key is the standard representation of an integer, it will be interpreted as such (i.e. "8" will be interpreted as 8, while "08" will be interpreted as "08"). Floats in key are truncated to integer. The indexed and associative array types are the same type in PHP, which can both contain integer and string indices.

A value can be any PHP type.

<?php
$arr 
= array("somearray" => array(=> 513 => 9"a" => 42));

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

If a key is not specified for a value, the maximum of the integer indices is taken and the new key will be that value plus 1. If a key that already has an assigned value is specified, that value will be overwritten.

<?php
// This array is the same as ...
array(=> 433256"b" => 12);

// ...this array
array(=> 43=> 32=> 56"b" => 12);
?>
Ostrzeżenie

Before PHP 4.3.0, appending to an array in which the current maximum key was negative would create a new key as described above. Since PHP 4.3.0, the new key will be 0.

Using TRUE as key will evaluate to integer 1 as a key. Using FALSE as key will evaluate to integer 0 as a key. Using NULL as a key will evaluate to the empty string. Using the empty string as a key will create (or overwrite) a key with the empty string and its value; it is not the same as using empty brackets.

Arrays and objects can not be used as keys. Doing so will result in a warning: Illegal offset type.

Creating/modifying with square bracket syntax

An existing array can be modified by explicitly setting values in it.

This is done by assigning values to the array, specifying the key in brackets. The key can also be omitted, resulting in an empty pair of brackets ([]).

$arr[key] = value;
$arr[] = value;
// key may be an integer or string
// value may be any value of any type

If $arr doesn't exist yet, it will be created, so this is also an alternative way to create an array. To change a certain value, assign a new value to that element using its key. To remove a key/value pair, call the unset() function on it.

<?php
$arr 
= array(=> 112 => 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
?>

Informacja: As mentioned above, if no key is specified, the maximum of the existing integer indices is taken, and the new key will be that maximum value plus 1. If no integer indices exist yet, the key will be 0 (zero). If a key that already has a value is specified, that value will be overwritten.
Note that the maximum integer key used for this need not currently exist in the array. It need only have existed in the array at some time since the last time the array was re-indexed. The following example illustrates:

<?php
// Create a simple array.
$array = array(12345);
print_r($array);

// Now delete every item, but leave the array itself intact:
foreach ($array as $i => $value) {
    unset(
$array[$i]);
}
print_r($array);

// Append an item (note that the new key is 5, instead of 0).
$array[] = 6;
print_r($array);

// Re-index:
$array array_values($array);
$array[] = 7;
print_r($array);
?>

Powyższy przykład wyświetli:

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

Useful functions

There are quite a few useful functions for working with arrays. See the array functions section.

Informacja: The unset() function allows removing keys from an array. Be aware that the array will not be reindexed. If a true "remove and shift" behavior is desired, the array can be reindexed using the array_values() function.

<?php
$a 
= array(=> 'one'=> 'two'=> 'three');
unset(
$a[2]);
/* will produce an array that would have been defined as
   $a = array(1 => 'one', 3 => 'three');
   and NOT
   $a = array(1 => 'one', 2 =>'three');
*/

$b array_values($a);
// Now $b is array(0 => 'one', 1 =>'three')
?>

The foreach control structure exists specifically for arrays. It provides an easy way to traverse an array.

Array do's and don'ts

Why is $foo[bar] wrong?

Always use quotes around a string literal array index. For example, $foo['bar'] is correct, while $foo[bar] is not. But why? It is common to encounter this kind of syntax in old scripts:

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

This is wrong, but it works. The reason is that this code has an undefined constant (bar) rather than a string ('bar' - notice the quotes). PHP may in future define constants which, unfortunately for such code, have the same name. It works because PHP automatically converts a bare string (an unquoted string which does not correspond to any known symbol) into a string which contains the bare string. For instance, if there is no defined constant named bar, then PHP will substitute in the string 'bar' and use that.

Informacja: This does not mean to always quote the key. Do not quote keys which are constants or variables, as this will prevent PHP from interpreting them.

<?php
error_reporting
(E_ALL);
ini_set('display_errors'true);
ini_set('html_errors'false);
// Simple array:
$array = array(12);
$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";
}
?>
Powyższy przykład wyświetli:
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

More examples to demonstrate this behaviour:

<?php
// Show all errors
error_reporting(E_ALL);

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

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

// Incorrect.  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

// This defines a constant to demonstrate what's going on.  The value 'veggie'
// is assigned 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 occurs here
print "Hello $arr[fruit]";      // Hello apple

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

// This will not work, and will result 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 superglobals in strings as well
print "Hello $arr['fruit']";
print 
"Hello $_GET['foo']";

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

When error_reporting is set to show E_NOTICE level errors (by setting it to E_ALL, for example), such uses will become immediately visible. By default, error_reporting is set not to show notices.

As stated in the syntax section, what's inside the square brackets ('[' and ']') must be an expression. This means that code like this works:

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

This is an example of using a function return value as the array index. PHP also knows about constants:

<?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";
?>

Note that E_ERROR is also a valid identifier, just like bar in the first example. But the last example is in fact the same as writing:

<?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";
?>

because E_ERROR equals 1, etc.

So why is it bad then?

At some point in the future, the PHP team might want to add another constant or keyword, or a constant in other code may interfere. For example, it is already wrong to use the words empty and default this way, since they are reserved keywords.

Informacja: To reiterate, inside a double-quoted string, it's valid to not surround array indexes with quotes so "$foo[bar]" is valid. See the above examples for details on why as well as the section on variable parsing in strings.

Converting to array

For any of the types: integer, float, string, boolean and resource, converting a value to an array results in an array with a single element with index zero and the value of the scalar which was converted. In other words, (array)$scalarValue is exactly the same as array($scalarValue).

If an object is converted to an array, the result is an array whose elements are the object's properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name. These prepended values have null bytes on either side. This can result in some unexpected behaviour:

<?php

class {
    private 
$A// This will become '\0A\0A'
}

class 
extends {
    private 
$A// This will become '\0B\0A'
    
public $AA// This will become 'AA'
}

var_dump((array) new B());
?>

The above will appear to have two keys named 'AA', although one of them is actually named '\0A\0A'.

Converting NULL to an array results in an empty array.

Comparing

It is possible to compare arrays with the array_diff() function and with array operators.

Examples

The array type in PHP is very versatile. Here are some examples:

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

$b = array('a''b''c');

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

$b = array();
$b[] = 'a';
$b[] = 'b';
$b[] = 'c';

// After the above code is executed, $a will be the array
// array('color' => 'red', 'taste' => 'sweet', 'shape' => 'round', 
// 'name' => 'apple', 0 => 4), and $b will be the array 
// array(0 => 'a', 1 => 'b', 2 => 'c'), or simply array('a', 'b', 'c').
?>

Example #1 Using 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();         
?>

Example #2 Collection

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

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

?>

Powyższy przykład wyświetli:

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

Changing the values of the array directly is possible since PHP 5 by passing them by reference. Before that, a workaround is necessary:

Example #3 Collection

<?php
// PHP 5
foreach ($colors as &$color) {
    
$color strtoupper($color);
}
unset(
$color); /* ensure that following writes to
$color will not modify the last array element */

// Workaround for older versions
foreach ($colors as $key => $color) {
    
$colors[$key] = strtoupper($color);
}

print_r($colors);
?>

Powyższy przykład wyświetli:

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

This example creates a one-based array.

Example #4 One-based index

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

Powyższy przykład wyświetli:

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

Example #5 Filling an array

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

Arrays are ordered. The order can be changed using various sorting functions. See the array functions section for more information. The count() function can be used to count the number of items in an array.

Example #6 Sorting an array

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

Because the value of an array can be anything, it can also be another array. This enables the creation of recursive and multi-dimensional arrays.

Example #7 Recursive and multi-dimensional arrays

<?php
$fruits 
= array ( "fruits"  => array ( "a" => "orange",
                                       
"b" => "banana",
                                       
"c" => "apple"
                                     
),
                  
"numbers" => array ( 1,
                                       
2,
                                       
3,
                                       
4,
                                       
5,
                                       
6
                                     
),
                  
"holes"   => array (      "first",
                                       
=> "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"
?>

Array assignment always involves value copying. Use the reference operator to copy an array by reference.

<?php
$arr1 
= array(23);
$arr2 $arr1;
$arr2[] = 4// $arr2 is changed,
             // $arr1 is still array(2, 3)
             
$arr3 = &$arr1;
$arr3[] = 4// now $arr1 and $arr3 are the same
?>


Objects> <Strings
Last updated: Fri, 02 Jan 2009
 
add a note add a note User Contributed Notes
Arrays
Dawid Krysiak
17-Dec-2008 03: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.
hek at theeks dot net
24-Oct-2008 08: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)
?>
pinkgothic at gmail dot com
13-Sep-2008 08: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."
frywater
04-Jun-2008 04: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
fmouse at fmp dot com
29-Apr-2008 01: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!
rama dot devi at gmail dot com
18-Mar-2008 02: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
ken underscore yap atsign email dot com
09-Jan-2008 08: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.
pepesantillan at gmail dot com
18-Dec-2007 04: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);
?>
SID TRIVEDI
10-Oct-2007 02: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!';

?>
carl at linkleaf dot com
06-Sep-2007 11: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.
Gautam
30-Aug-2007 01: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.
?>
Olegk, getmequick[at]gmail[dot]com
21-Aug-2007 02: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+);       
        }   
    }

    return
$ret;

}

?>

Hope this will help someone!
conorj
14-Jul-2007 08: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]";
moehbass at gmail dot com
10-Jul-2007 05: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!
don dot hosek at gmail dot com
23-May-2007 05: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
lesantoso at yahoo dot com
20-Mar-2007 03: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
Spudley
16-Mar-2007 02: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.
kal at kalunite dot com i mean dot net
16-Jan-2007 05: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?)
25-Oct-2006 09: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
27-Sep-2006 02: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 08: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
25-Jul-2006 04: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
08-Jun-2006 11: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 06: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
09-May-2006 01: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 b