★ wanayoo — archive 1999 http://fr.php.net/manual/en/function.array.phpNouvelle recherche | Portail wanayoo
PHP  
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links 
search for in the  
previousarray_walkarsortnext
Last updated: Thu, 15 Aug 2002
view the printer friendly version or the printer friendly version with notes or change language to Brazilian Portuguese | Chinese | Czech | Dutch | Finnish | French | German | Hungarian | Italian | Japanese | Korean | Polish | Romanian | Russian | Spanish | Turkish

array

(unknown)

array --  Create an array

Description

array array ( [mixed ...])

Returns an array of the parameters. The parameters can be given an index with the => operator.

Note: array() is a language construct used to represent literal arrays, and not a regular function.

Syntax "index => values", separated by commas, define index and values. index may be of type string or numeric. When index is omitted, a integer index is automatically generated, starting at 0. If index is an integer, next generated index will be the biggest integer index + 1. Note that when two identical index are defined, the last overwrite the first.

The following example demonstrates how to create a two-dimensional array, how to specify keys for associative arrays, and how to skip-and-continue numeric indices in normal arrays.

Example 1. array() example

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

Example 2. Automatic index with array()

$array = array( 1, 1, 1, 1,  1, 8=>1,  4=>1, 19, 3=>13);
print_r($array);

will display :
Array
(
    [0] => 1
    [1] => 1
    [2] => 1
    [3] => 13
    [4] => 1
    [8] => 1
    [9] => 19
)

Note that index '3' is defined twice, and keep its final value of 13. Index 4 is defined after index 8, and next generated index (value 19) is 9, since biggest index was 8.

This example creates a 1-based array.

Example 3. 1-based index with array()

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

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

See also array_pad(), list(), and range().

User Contributed Notes
array
add a note about notes
baghera@mindspring.com
12-Oct-1999 08:54

Every array has an "internal pointer". When you create an array, the internal pointer is automatically set to point at the first member. You can print the current location of the pointer:

$bob= current($myarrayname);
echo "$bob";

You can advance the pointer to the next spot using next($myarrayname).

To see a particular member of an array, set a $variable= $myarrayname[2] where "2" is the number of the member you want to use.

When assigning members to an array, the members are numbered beginning with 0, rather than 1.

php-manual@improbable.org
02-Apr-2000 09:17

If you want to create an array of a set size and you have PHP4, use array_pad(array(), $SIZE, $INITIAL_VALUE); This can be handy if you wish to initialize a bunch of variables at once:

list($Var1, $Var2, etc) = array_pad(array(), $NUMBER_OF_VARS, $INITIAL_VALUE);

innuedo@...
25-Jul-2000 08:09

To determine the size of an array without using a while loop, use sizeof().
rubein@earthlink.net
26-Sep-2000 05:07

Multidimensional arrays are actually single-dimensional arrays nested inside other single-dimensional arrays.

$array[0] refers to element 0 of $array
$array[0][2] refers to element 2 of element 0 of $array.

If an array was initialized like this:

$array[0] = "foo";
$array[1][0] = "bar";
$array[1][1] = "baz";
$array[1][2] = "bam";

then:
is_array($array) = TRUE
is_array($array[0]) = FALSE
is_array($array[1]) = TRUE
count($array) = 2 (elements 0 and 1)
count($array[1] = 3 (elements 0 thru 2)

This can be really useful if you want to return a list of arrays that were stored in a file or something:

$array[0] = unserialize($somedata);
$array[1] = unserialize($someotherdata);

if $somedata["foo"] = 42 before it was serialized previously, you'd now have this:
$array[0]["foo"] = 42

jasonr@argia.net
27-Nov-2000 11:01

Arrays are never removed from memory, however there is an internal pointer that always points to the "next" array item. After you interate through an array, this will need to be reset back to the first element if you want to access it in a loop again.
see the Reset function at
http://www.php.net/manual/function.reset.php if you are confused.

atrox@screaming-penguin.com
11-Feb-2001 03:40

actually it is quite easy to directly reference a value in an array relatively.
you simply must reset and sort the array first (see reset and sort)

also note that when using dynamically assigned arrays that potentially may have only one element, sort does not re-index the array from zero, so in each case where an array could potentially only have one element you must count the array, if it has one element then re-assign it with an index of zero (to ensure that it is zero after it is processed) if it has more than one element then sort will do the work for you: example:

reset($array);
sort($array);
$count = count($array);
if ($count == 1)
{
$value = current($array);
$array = array ("0" => "$value");
}

in this manner the array is reset and sorted FIRST and then counted, if the count is 1, then it is rebuilt with an index of 0 (note that sort re-indexes beggining with 0 if the array has multiple elements)

slicky@newshelix.com
20-Mar-2001 07:57

Notice that you can also add arrays to other arrays with the $array[] "operator" while the dimension doesn't matter.

Here's an example:
$x[w][x] = $y[y][z];
this will give you a 4dimensional assosiative array.
$x[][] = $y[][];
this will give you a 4dimensional non assosiative array.

So let me come to the point. This get interessting for shortening things up. For instance:
foreach ($lines as $line){
if(!trim($line)) continue;
$tds[] = explode("$delimiter",$line);
}

xftp@yahoo.com
22-May-2001 02:18

This is a small script that shows how to use an array of a Class.

<?

class test{
var $test1;
var $test2;
}


$a = array();
$a[] = new test;

$a[0]->$test1 = 1;
$a[0]->$test2 = 1;

$a[1]->$test1 = 2;
$a[1]->$test2 = 2;


$x = $a[0]->$test1;
$y = $a[0]->$test2;

echo "$x - $y";

?>

joshua.e@usa.net
24-May-2001 05:12

Here's a cool tip for working with associative arrays-
Here's what I was trying to accomplish:

I wanted to hit a DB, and load the results into an associative array, since I only had key/value pairs returned. I loaded them into an array, because I wanted to manipulate the data further after the DB select, but I didn't want to hit the DB more than necessary.

Here's how I did it:

//assume db connectivity
//load it all into the associative array
$sql = "SELECT key,value FROM table";
$result = mysql_query($sql);
while($row = mysql_fetch_row($result)) {
$myArray[$row[0]] = $row[1];
}
//now we expand it
while(list($key,$value) = each($myArray)) {
echo "$key : $value";
}

I found this to be super efficient, and extremely cool.

deepak_pradhan@yahoo.com
15-Sep-2001 11:16

I have seen that most of the time we get confused with Mult-Dimensional arrays.
I found print_r to be very helpful here.

Say the defined array is:
$a = array(1,2,array("A","B"));

print_r ($a);
Should give result like this:
Array ( [0] => 1 [1] => 2 [2] => Array ( [0] => A [1] => B ) )
We can see here that:
$a is an array, $a[0]=1, $a[1]=2 and $a[2]=array it self with two elements.


thx
dp

tobiasquinteiro@ig.com.br
29-Jan-2002 06:25

<?
// This is a small script that shows how to use an multiple array
for($x = 0;$x < 10;$x++){
for($y = 0;$y < 10;$y++){
$mat[$x][$y] = "$x,$y";
}
}

for($x = 0;$x < count($mat);$x++){
for($y = 0;$y < count($mat[$x]);$y++){
echo "mat[$x][$y]: " .
$mat[$x][$y] . " ";
}
echo "\n";
}
?>

jjm152@hotmail.com
11-Mar-2002 12:22

The easiest way to "list" the values of either a normal 1 list array or a multi dimensional array is to use a foreach() clause.

Example for 1 dim array:

$arr = array( 1, 2, 3, 4, 5 );
foreach ( $arr as $val ) {
echo "Value: $Val\n";
}

For multi dim array:
$arr = array( 1 => 'one', 2 => 'two', 3 => 'three', 4 => 'four, 5 => 'five');
foreach ( $arr as $key => $value ) {
echo "Key: $key, Value: $value\n";
}

This is quite possibly the easiest way i've found to iterate through an array.

TheCoder@163.com
12-Apr-2002 03:56

It looks like array() does not support double byte chars,I am in china,I can't use this code:
$test = array('Chinese word here' = > '1','Another chinese word'=>'2');
if I use chinese word in array ,there are errors.

jay@ezlasvegas.net
20-Apr-2002 10:21

If you want to create an array of a set size and you have PHP4, use
array_pad(array(), $SIZE, $INITIAL_VALUE); This can be handy if you wish
to initialize a bunch of variables at once:

list($Var1, $Var2, etc) = array_pad(array(), $NUMBER_OF_VARS,
$INITIAL_VALUE);

Jay Walker
Las Vegas Hotel Associate
http://www.ezlasvegas.net

bjarte_at_gandtech_dot_com
14-May-2002 10:49

I got tired of trying to find a function to add a entry to the "top"/index 0 to a array the i made a function for it.

function fc_array_add_first($in_array, $in_value) {
$f_arout = array();
$f_arout[] = $in_value;
foreach ($in_array as $key => $value) {
$f_arout[] = $value;
}
return $f_arout;
}

Markus.Elfring@web.de
30-May-2002 09:04

It seems to me that the use of brackets with multidimensional arrays is not described here.

But the following examples work:
$value = $point['x']['y'];
$message[1][2][3] = 'Greetings';

powerpnt@yucom.DONT_SPAM.be
09-Jun-2002 10:35

There's a little mistake in the class-example of xftp@yahoo.com.

In php you only use 1 dollar sign for a variable, this means
$a[0]->$test1 = 1;
should be:
$a[0]->test1 = 1;

Same thing for every other of the class variables references.

Pongo
20-Jun-2002 05:49

Be careful when you try to access an instance array variable inside of double quotes (a common Perl practice). Several hours of debugging led me to conclude that this:

echo( "The value: $this->someArray[1]" )

simply will not work. Make sure the array reference is outside the quotes!

john
18-Jul-2002 04:35

here's a nice short/lazy way to create an array:

function ar($combos) {
$choices = explode("|", $combos);
foreach ($choices as $choice) {
list($short, $long) = explode(":", $choice);
$john[$short] = $long;
}
return $john;
}

$genders = ar("M:Male|F:Female");
// $genders['M'] = 'Male';
// $genders['F'] = 'Female';

John
18-Jul-2002 05:48

Be careful not to create an array on top of an already existing variable:

$name = "John";
$name['last'] = "Doe";

$name becomes "Dohn" since 'last' evaluates to the 0th position of $name.
Same is true for multi-arrays.

cteubnerNOSPAM@NOSPAMncw-av.com
29-Jul-2002 09:22

The function listed above for adding to the beginning of an array is thorougly unnecessary; use array_unshift() instead, which I guarantee is faster since PHP arrays aren't really arrays but instead are linked lists.

This means that the thing that's unshifted needs only have its pointer set to point at the beginning of the array, and the array's pointer set to point at the new element. The example function above recopies every element in the array, which you need only do if you're working with contiguous storage, something PHP doesn't offer.

add a note about notes
previousarray_walkarsortnext
Last updated: Thu, 15 Aug 2002
show source | credits | stats | mirror sites
Copyright © 2001, 2002 The PHP Group
All rights reserved.
This mirror generously provided by: nexen.net
Last updated: Sun Aug 18 04:45:58 2002 CEST