PHP  
downloads | documentation | faq | getting help | | php.net sites | links 
search for in the  
previousvirtualarraynext
Last updated: Tue, 28 May 2002
view this page in Printer friendly version | English | Brazilian Portuguese | Czech | Dutch | French | German | Hungarian | Italian | Japanese | Korean | Polish | Romanian | Russian | Spanish | Turkish

II. Array Functions

Introduction

These functions allow you to interact with and manipulate arrays in various ways. Arrays are essential for storing, managing, and operating on sets of variables.

Simple and multi-dimensional arrays are supported, and may be either user created or created by another function. There are specific database handling functions for populating arrays from database queries, and several functions return arrays.

Please see the Arrays section of the manual for a detailed explanation of how arrays are implemented and used in PHP.

Requirements

These functions are available as part of the standard module, which is always available.

Installation

There is no installation needed to use these functions, they are part of the PHP core.

Runtime Configuration

T�m� laajennus ei m��rittele yht�k��n konfigurointi asetusta.

Resource Types

T�m� laajennus ei m��rittele yht�k��n resurssi-tyyppi�.

Predefined Constants

CASE_UPPER and CASE_LOWER are used with the array_change_key_case() function. They respectively are used for changing a string to upper case or lower case.

Sis�llys
array --  Create an array
array_change_key_case -- Returns an array with all string keys lowercased or uppercased
array_chunk -- Split an array into chunks
array_count_values -- Counts all the values of an array
array_diff -- Computes the difference of arrays
array_fill -- Fill an array with values
array_filter --  Filters elements of an array using a callback function
array_flip -- Flip all the values of an array
array_intersect -- Computes the intersection of arrays
array_key_exists -- Checks if the given key or index exists in the array
array_keys -- Return all the keys of an array
array_map --  Applies the callback to the elements of the given arrays
array_merge -- Merge two or more arrays
array_merge_recursive -- Merge two or more arrays recursively
array_multisort -- Sort multiple or multi-dimensional arrays
array_pad --  Pad array to the specified length with a value
array_pop -- Pop the element off the end of array
array_push --  Push one or more elements onto the end of array
array_rand --  Pick one or more random entries out of an array
array_reduce --  Iteratively reduce the array to a single value using a callback function
array_reverse --  Return an array with elements in reverse order
array_search --  Searches the array for a given value and returns the corresponding key if successful
array_shift --  Shift an element off the beginning of array
array_slice -- Extract a slice of the array
array_splice --  Remove a portion of the array and replace it with something else
array_sum --  Calculate the sum of values in an array.
array_unique -- Removes duplicate values from an array
array_unshift --  Prepend one or more elements to the beginning of array
array_values -- Return all the values of an array
array_walk --  Apply a user function to every member of an array
arsort --  Sort an array in reverse order and maintain index association
asort -- Sort an array and maintain index association
compact --  Create array containing variables and their values
count -- Count elements in a variable
current -- Return the current element in an array
each --  Return the current key and value pair from an array and advance the array cursor
end --  Set the internal pointer of an array to its last element
extract --  Import variables into the current symbol table from an array
in_array -- Return TRUE if a value exists in an array
key -- Fetch a key from an associative array
krsort -- Sort an array by key in reverse order
ksort -- Sort an array by key
list --  Assign variables as if they were an array
natcasesort --  Sort an array using a case insensitive "natural order" algorithm
natsort --  Sort an array using a "natural order" algorithm
next --  Advance the internal array pointer of an array
pos -- Get the current element from an array
prev -- Rewind the internal array pointer
range --  Create an array containing a range of elements
reset --  Set the internal pointer of an array to its first element
rsort -- Sort an array in reverse order
shuffle -- Shuffle an array
sizeof -- Get the number of elements in variable
sort -- Sort an array
uasort --  Sort an array with a user-defined comparison function and maintain index association
uksort --  Sort an array by keys using a user-defined comparison function
usort --  Sort an array by values using a user-defined comparison function
User Contributed Notes
Array Functions
add a note about notes

01-Feb-1999 12:30

use the max function to get the highest value of an array e.g:
   $maxval = max($array);


04-Apr-2001 09:58

I added this note to array_pop, but it's probably more applicable here:

If you use array_pop, the numeric indices  will be renumbered if there are
any gaps. So if you start with

$a[5]="five"; 
$a[6]="six"; 

and then do array_pop($a), you now have $a[0]="five", not
$a[5]="five", as you might expect. In other words, $a does not
necessarily equal array_pop(array_push($a, 1)).

Response in the bug database was the following:

--
Presently, all splice-derived functions reorder numeric keys. There's not
much to do about it, since it's the way Zend Engine handles numeric hash
keys. Changing it either way won't bring more consistent  functionality,
so in the meantime it is just as it is.
--

I'd disagree that changing my array indices is consistent, but there you
are. I don't know which array functions are splice-derived, so look out
for this.


29-Aug-2001 07:58

You should really read 
, there is a lot of info there about how to handle arrays, how to check
wether indices are set, how to modify an array, anything.


29-Jan-2002 09:55

You should pay attention to the fact that some functions act directly on
the array (such as asort) and some don't touch the array but return a copy
(such as array_reverse).  If you use one in the improper context you won't
get a warning. It took me a while to notice this as I do a lot of coding
by memory and don't refer to the function documentation unless I need to.


05-Feb-2002 05:56

To display the value of a variable from a two dimentional array inside a
quoted string, use the following syntax:

<?php

$var = array(
    'name' => array(
        'first' => 'Caleb',
        'last' => 'Maclennan'
      )
  );

echo "My first name is {$var[name][first]}!";

?>


14-Apr-2002 09:34

Looping through an array, and printing each item:

for ($i = 0; $i < count($array_name); $i++) { echo("$i -
$arrayname[$i]"); }


20-Apr-2002 12:43

You should pay attention to the fact that some functions act directly on
the array (such as asort) and some don't touch the array but return a
copy
(such as array_reverse).

Tim Burly


13-May-2002 07:12

I bet there was someone else that needed to translate an associative array
from php into, lets say, an associative array in JavaScript (or other
programing language)
You can use these functions i wrote, which i tried to be as customizable
as possible, for use in many other languages.

For example, in JavaScript an associative array would look like:

array: {
    category1: {
        title: 'cat title 1',
        name: 'cat_name_1',
        desc: 'cat desc 1'
    },
    category2: {
        title: 'cat title 2',
        name: 'cat_name_2',
        desc: 'cat desc 2'
    },
    property: value
}

Here are the functions i wrote: (legend at the end)

function ga($arr, $sep, $grp, $elemsep, $end, $ind, $indpos) {
	$newarr = "";
	foreach( $arr as $key=>$val ) {
		
		if( is_array( $val ) ) {
		
			$newarr .= str_repeat( $ind, $indpos ).$key.$sep.$grp[0].$end;
			$newarr .= ga( $val, $sep, $grp, $elemsep, $end, $ind, $indpos + 1 );
			$newarr .= str_repeat( $ind, $indpos ).$grp[1];
		}
		else
			$newarr .= str_repeat( $ind, $indpos ).$key.$sep.$val;
	
		$newarr .= ( ( $arr[$key] == end( $arr ) ) ? "" : $elemsep ) .
$end;
	}

	return $newarr;
}

function genarr( $arrname, $genfunc, $sep = ": ", $grp = array(
"{", "}" ) , $elemsep = ",", $end =
"\n", $ind = "\t", $indpos = 1 ) {
	global $$arrname;
	return $arrname.$sep.$grp[0].$end.$genfunc ($$arrname, $sep, $grp,
$elemsep, $end, $ind, $indpos).$grp[1];
}

Legend:

$arr = the php associative array to transform

$sep = the separator char/string between the key and the value (in
JavaScript its ":", in PHP its "=>")

$grp = an array having the 1st element as the "new array"
character and the 2nd element as the "array end" character (in
javaScript they are "{" and "}", in PHP they are
"array(" and ")" )

$elemsep = elements separator (in javascript and PHP its "," )

$end = the caracter appended at the end of an element

$ind = indentation character

$indpos = default indent 

NOTE: if you would like an inline output, then set the $end = ""
and the $ind = "".
If you want a stylish output you can set the $end = "\n" and
$ind = "\t".

$genfunc = a STRING evaluating to the the fetching function name (in this
case "ga")

$arrname = a STRING, evaluating to the array variable name (note the
calling to it by "$$arrname" )

NOTE: for JavaScript, i set all arguments by default in the
"genarr" function.

EXAMPLE:

Supposing you have a PHP associative array:

$bob = array( 
    "key1" => array (
         ......

then for javaScript, you should call the "genarr" function like
this:

$JSArray = genarr( "bob", "ga" )

note the arguments: "bob" and "ga"

This will result in a Javascript array like this:

bob: {
    key1: {
       .....

Hope it helped because i need to have a huge JavaScript associative array
for one of the sites i run but also the same array in PHP and its a hell
of a job updating 2 pieces of code when PHP can generate it dynamically,
thus its sufficient to make changes only in the PHP code.

Cheers

P.S. let me know if you found it useful


13-May-2002 10:51

In the last post i missed something in the fetching function. It had
troubles handling boolean values and i forgot strings as well. Also,
detecting the end of a sub-array didnt work as expected. Here are the new
versions that worked with everything i threw at it:

function ga($arr, $sep, $grp, $elemsep, $str, $end, $ind, $indpos) {

	$newarr = "";
	$len = count( $arr );
	for( $i=0; $i<$len; $i++ ) {

		//get current key,value pair
		list( $key, $val ) = each( $arr );
		
		if( is_array( $val ) ) {
			//calling recursively if it hits a sub-array
			$newarr .= str_repeat( $ind, $indpos ).$key.$sep.$grp[0].$end;
			$newarr .= ga( $val, $sep, $grp, $elemsep, $str, $end, $ind, $indpos +
1 );
			$newarr .= str_repeat( $ind, $indpos ).$grp[1];
		}
		else {
			$newarr .= str_repeat( $ind, $indpos ).$key.$sep;
			//determine element type
			$newarr .= ( is_bool( $val ) ) ? (($val) ? 'true' : 'false') : (
is_string( $val ) ? $str.addslashes( $val ).$str : $val );
		}

		//if last element then don't add $elemsep after it
		$newarr .= ( $i == $len-1 ) ? $end : $elemsep.$end;
	}

	return $newarr;
}

	
function genarr( $arrname, $genfunc, $sep = ': ', $grp = array( '{', '}' )
, $elemsep = ',', $str = '"', $end = "\r\n", $ind =
"\t", $indpos = 1 ) {
	global $$arrname;
	return $arrname.$sep.$grp[0].$end.$genfunc ($$arrname, $sep, $grp,
$elemsep, $str, $end, $ind, $indpos).$grp[1];
}

I also added addslashes() to string values. There is a new argument:

$str = the string delimiter (usually " \" " or " \'
" ). The second function only has the new argument modified. The rest
is the same.

Please let me know if you find anything going wrong.

Cheers


28-May-2002 04:10

here's a little function i wrote to convert any multidimensional array to
an xml tree. it has this prototype:

string arr2xml (array array, [string tree_name])

if they are associative arrays, the element keys will be used as node
names. any numeric arrays will be filled in with level1, level2 .. if you
omit the second (optional) argument, it uses level0 as the top of the
tree.

function arr2xml ($arr)
{
   if (func_num_args () < 3)
   {
      $wrapper = (func_num_args < 2) ? array ($arr) : array
(func_get_arg(1)=>$arr);
      $xml = arr2xml ($wrapper, '', 0);
   }
   else
   {
      $level = func_get_arg (2);
      while (list ($key, $val) = each ($arr))
      {
         if ($key === (int)$key) $key = 'level'.$level;
         $xml .= '<'.$key.'>';
         if (gettype ($val) == 'array')
         {
            $xml .= arr2xml ($val, '', $level+1);
         }
            else
         {
            $xml .= $val;
         }
         $xml .= '</'.$key.'>';
      }
   }
   return $xml;
}


29-May-2002 02:17

could an admin please remove my last post? this is a much better rewrite of
the arr2xml () function.

its more sensibly written and flexible now. theres only one required
argument, the array itself. it has this prototype: 

string arr2xml (array array, [string tree_name], [[int level]) 

use the second argument if you want to specify a name for the top of the
tree - otherwise it defaults to level0. the first call to the function is
kind of a dummy top level that wraps the array inside another array and
calls the function for real. 

dont use the third argument. thats used to keep track of the levels in all
the recursive calls. 

heres the code: 

function arr2xml ($arr)
{
   if (func_num_args () < 3)
   {
      $wrapper = (func_num_args < 2) ? array ($arr) : array
(func_get_arg(1)=>$arr);
      $xml = arr2xml ($wrapper, '', 0);
   }
   else
   {
      $level = func_get_arg (2);
      while (list ($key, $val) = each ($arr))
      {
         if ($key === (int)$key) $key = 'level'.$level;
         $xml .= '<'.$key.'>';
         if (gettype ($val) == 'array')
         {
            $xml .= arr2xml ($val, '', $level+1);
         }
            else
         {
            $xml .= $val;
         }
         $xml .= '</'.$key.'>';
      }
   }
   return $xml;
}

bishop
07-Jun-2002 05:42

Sometimes you need an array that has all keys exactly equal to all values. 
For example, arrays that look like:
array('a' => 'a', 'b' => 'b', 'c' => 'c');

You can either do it manually (a pain for count($a) > 2), or use
array_smear():

/* smear values across into keys, or vice-versa */
function array_smear($a, $v2k = true) {
    $values = ($v2k) ? array_values($a) : array_keys($a);

    $a = array();
    foreach ($values as $v)
        $a[$v] = $v;

    return ($a);
}

array_smear takes an array, then a boolean specifying whether you want to
smear the values over into the keys (the default, and probably what you
usually want) or vice-versa.

So:
$a = array('a', 'b', 'c');

$x = array_smear($a);
// x == array('a' => 'a', 'b' => 'b', 'c' => 'c');

$y = array_smear($a, false);
// y == array(0 => 0, 1 => 1, 2 => 2);


13-Jun-2002 09:13

I am working on a project wherein I had to delete something from an array,
but I couldn't leave a hole in the array.
For example:
<?php
$myarray[0] = "test0";
$myarray[1] = "test1";
$myarray[2] = "test2";

unset($myarray[1]);
for($i=0;$i<count($myarray);$i++) {
echo $i." = ".$myarray[$i]."
"; } /* Outputs this: 0 = test0 1 = */ ?> Obviously, that doesn't work. ;) I won't explain why, but you can probably figure that out yourself. Anyway, I wrote a function to correct this problem: <?php function deleteandpush($array, $indice) { unset($array[$indice]); for($i=0;$i<count($array);$i++) { if(!isset($array[$i])) { $array[$i] = $array[$i+1]; unset($array[$i+1]); }; } return $array; } $myarray[0] = "test0"; $myarray[1] = "test1"; $myarray[2] = "test2"; $myarray[3] = "test3"; $myarray[4] = "test4"; $array = deleteandpush($myarray, 3); for($i=0;$i<count($array);$i++) { echo $i.":".$array[$i]."
"; } /* Outputs: 0:test0 1:test1 2:test2 3:test4 */ ?> Hope this helps someone.

spam (at) speedcapture . com
15-Jun-2002 01:50

I want to share a VERY usefull way to debug php and arrays:

just create a file like array.func.inc.php

paste the following code into the file.

// To make ANY array visible ...

function viewArray($arr)
{
    echo '<table cellpadding="0" cellspacing="0"
border="1">';
    foreach ($arr as $key1 => $elem1) {
        echo '<tr>';
        echo '<td>'.$key1.'&nbsp;</td>';
        if (is_array($elem1)) { extArray($elem1); }
        else { echo '<td>'.$elem1.'&nbsp;</td>'; }
        echo '</tr>';
    }
    echo '</table>';
}

function extArray($arr)
{
    echo '<td>';
    echo '<table cellpadding="0" cellspacing="0"
border="1">';
    foreach ($arr as $key => $elem) {
        echo '<tr>';
        echo '<td>'.$key.'&nbsp;</td>';
        if (is_array($elem)) { extArray($elem);	}
        else { echo
'<td>'.htmlspecialchars($elem).'&nbsp;</td>'; }
        echo '</tr>';
    }
    echo '</table>';
    echo '</td>';
}

close the file and include that file into any other php document. If u
want to check the content of an array just type viewarray($array);

webkid%webkid.com
19-Jun-2002 05:47

A painstakenly written function to add a "value" to a recursive
array using a pathlist (also in the format of an array):

function recurse($a,$rm,$k,$d){ if (sizeof($rm)==0){$a[$k]=$d;
return ($a);}
$sh=array_shift($rm); $a[$sh]=recurse ($a[$sh],$rm,$k,$d);
return ($a);}

Called like this: $ary=recurse($ary,
array("level1","level2","level3"),"key",$value);

So an array like
Array(
    [0] => a
    [1] => b
    [2] => c
    [d] => Array
        (   [0] => a
            [1] => b
            [c] => Array
                (   [0] => e
                    [1] => f
                    [2] => g
                    [3] => h
                    [i] => Array
                        (   [0] => n
                        ) ) ) )
Can become
Array(
    [0] => a
    [1] => b
    [2] => c
    [d] => Array
        (   [0] => a
            [1] => b
            [c] => Array
                (   [0] => e
                    [1] => f
                    [2] => g
                    [3] => h
                    [i] => Array
                        (   [0] => n
                            [key] => data
                        ) ) ) )
With the call 
$ary=recurse($ary,array("d","c","i"),"key","data");


21-Jun-2002 05:14

<?

$myarray = array();

$myarray[1] = 1;
$myarray[2] = 2;
$myarray[3] = 3;
$myarray[4] = 4;

// I want to move $myarray[2] to the 4th position.

$ordered_array = reposition($myarray, 2,4);

foreach($ordered_array as $key=>$value){
	echo "ordered_array[$key] = $value";
}

?>

// The output of this function will be:

ordered_array[1] = 1
ordered_array[2] = 4
ordered_array[3] = 2
ordered_array[4] = 3

<?

function reposition($myarray,$myarray_key,$newpos){

	$oldpos = $myarray[$myarray_key];

	foreach($myarray as $key=>$value){
		if($key==$myarray_key){
			$myarray[$key] = $newpos;
		}else{

			if($oldpos>=$newpos){  // It's moving up the array

				// Values following it will go down (lower position)

				if($myarray[$key]<=$oldpos && $myarray[$key]>=$newpos){
					$myarray[$key]++;
				}

			}else{	// It's moving down the array

				// Values preceding it will go up (higher position)

				if($myarray[$key]>=$oldpos && $myarray[$key]<=$newpos){
					$myarray[$key]--;
				}
			}
		}
	}
	return $myarray;
}

?>

add a note about notes
previousvirtualarraynext
Last updated: Tue, 28 May 2002
show source | credits | stats | mirror sites:  
Copyright © 2001, 2002 The PHP Group
All rights reserved.
This mirror generously provided by:
Last updated: Thu Jul 4 12:06:15 2002 CEST