★ wanayoo — archive 1999 http://fr.php.net/manual/fr/function.array.phpNouvelle recherche | Portail wanayoo
PHP  
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links 
search for in the  
<array_walkarsort>
Last updated: Wed, 15 Jan 2003
view the printer friendly version or the printer friendly version with notes or change language to English | Brazilian Portuguese | Chinese (Simplified) | Chinese (Hong Kong Cantonese) | Chinese (Traditional) | Czech | Dutch | Finnish | German | Hebrew | Hungarian | Italian | Japanese | Korean | Polish | Romanian | Russian | Slovak | Slovenian | Spanish | Swedish | Turkish

array

(PHP 3, PHP 4 )

array --  Crée un tableau

Description

array array ( [mixed ...])

array() retourne un tableau créé avec les paramètres passés. On peut attribuer un index particulier à une valeur avec l'opérateur =?>.

Note : array() est un élément de langage utilisé pour représenter des tableaux litéraux, et non pas une fonction au sens strict du terme.

La syntaxe "index => valeur", séparée par des virgules, définit les index et leur valeur. Un index peut être une chaîne ou un nombre. Si l'index est omis, un index numérique sera automatiquement généré (commençant à 0). Si l'index est un entier, le prochain index généré prendra la valeur d'index la plus grande + 1. Notez que si deux index identiques sont définis, le dernier remplacera le premier.

L'exemple suivant montre comment créer un tableau à deux dimensions, comment spécifier les index d'un tableau associatif, et comment générer automatiquement des index numériques.

Exemple 1. Exemple avec array()

<?php
  $fruits = array (
    "fruits"  => array ("a" => "orange", "b" => "banane", "c" => "pomme"),
    "numbres" => array (1, 2, 3, 4, 5, 6),
    "trous"   => array ("premier", 5 => "deuxième", "troisième")
  );
?>

Exemple 2. Index automatique d'un tableau avec array()

<?php
  $array = array( 1, 1, 1, 1,  1, 8=>1,  4=>1, 19, 3=>13);
  print_r($array);
?>
qui affichera :

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

Notez bien que l'index '3' est défini deux fois, et conserve finalement sa dernière valeur de 13. L'index '4' est défini après l'index '8', et l'index généré suivant (valeur 19) est 9, puisque le plus grand index est alors 8.

Cet exemple crée un tableau dont les index commencent à 1.

Exemple 3. Tableau d'index commençant à 1

<?php
  $firstquarter  = array(1 => 'Janvier', 'Février', 'Mars');
  print_r($firstquarter);
?>
qui affichera :

Array
     (
     [1] => 'Janvier'
     [2] => 'Février'
     [3] => 'Mars'
     )

Voir aussi list().

User Contributed Notes
array
add a note about notes
baghera at mindspring dot com
12-Oct-1999 09: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 at improbable dot org
02-Apr-2000 10: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 at dot dot dot
25-Jul-2000 09:09

To determine the size of an array without using a while loop, use sizeof().
rubein at earthlink dot net
26-Sep-2000 06: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 at argia dot net
28-Nov-2000 12: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 at screaming-penguin dot com
11-Feb-2001 04: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 at newshelix dot com
20-Mar-2001 08: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 at yahoo dot com
22-May-2001 03: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 dot e at usa dot net
24-May-2001 06: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 at yahoo dot com
16-Sep-2001 12: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 at ig dot com dot br
29-Jan-2002 07: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 at hotmail dot com
11-Mar-2002 01: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 at 163 dot com
12-Apr-2002 04: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 at ezlasvegas dot net
20-Apr-2002 11: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 11: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 dot Elfring at web dot de
30-May-2002 10: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 at yucom dot DONT_SPAM dot be
09-Jun-2002 11: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 06: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 05: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 06: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 at NOSPAMncw-av dot com
29-Jul-2002 10: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.

bastiaens at skynet dot be
22-Aug-2002 03:08

In reply to Pongo (20-Jun-2002), his comment also applies to more-dimentional arrays:

Something like print "$blah[1][2]"; won't work, but $blih=$blah[1][2]; print "$blih"; works fine.

wojprzy at enternet dot pl
07-Sep-2002 09:30

In reply to bastiaens@skynet.be (22-Aug 2002). Instead of:

<? echo "Blam blam $blah[0][1]" ; ?>

try:

<? echo "Blam blam {$blah[0][1]}"; ?>

Works ok :). Regards, Wojtek

mads at __nospam__westermann dot dk
23-Oct-2002 02:39

In PHP 4.2.3 (and maybe earlier versions) arrays with numeric indexes may be initialized to start at a specific index and then automatically increment the index. This will save you having to write the index in front of every element for arrays that are not zero-based.

The code:

                 $a = array
(
21 => 1,
2,
3,
);
print '<pre>';
print_r($a);
print '</pre>';

will print:

Array
(
   [21] => 1
   [22] => 2
  [23] => 3
)

MadLogic at Paradise dot net dot nz
31-Oct-2002 09:39

Heres a simple yet intelligent way of setting an array, grabbing the values from the array using a loop.

$ary = array("1"=>'One','Two',"3"=>'Three');
$a = '0'; $b = count($ary);
while ($a <= $b) {
 $pr = $ary[$a];
print "$pr
";
 $a++;
}

mads at __nospam__westermann dot dk
22-Nov-2002 05:12

You cannot do:

print array('zero','one´','two','tree')[1];

This will yeild a parse error.

grubby_d at yahoo dot com
06-Dec-2002 05:58

About NULL as an array index.

An interesting thing with arrays is that you can use NULL as an index. I am trying it out with drop down list which will be used to update a database. Its not that good of an idea but it made me find the solution. For the database example you want to use the index "NULL" with quotes.

Say you have table person which has a foreign key reference to companies. BUT you want to allow the user to not specify a company as well. So you have determined that the database reference allows NULLs.

So you make a SELECT control with the lookup values as:

<OPTION value=(comp_id)>comp_name</OPTION>

using a while loop to print out the values.

Then you want the option to select NONE of the options. If you use something like -1 or 0 to represent this "blank" option you have to handle that in your php. Instead add this to your array: myarray("NULL") = "-none-" and you will get a field like this:

<OPTION value=NULL>-none-</OPTION>

Now every value from your SELECT control will be valid for the database and wont cause a foreign key references violation. it doesnt guarantee the data is coming from your trusty SELECT box so you still may want to check anyway.

Some interesting things about using the real NULL value as an array index:

$myarray = array(1, 2, 3);

echo count($myarray) . "
";  // 3
$myarray[NULL] = "the null value";
echo count($myarray) . "
";  // 4

if (array_key_exists(NULL, $myarray)
{ echo "this code will never be reached";}

This will return FALSE and will generate this warning:

Warning: Wrong datatype for first argument in call to array_key_exists

add a note about notes

<array_walkarsort>
Last updated: Wed, 15 Jan 2003
show source | credits | stats | mirror sites 
Copyright © 2001-2003 The PHP Group
All rights reserved.
This mirror generously provided by: nexen.net
Last updated: Thu Jan 30 04:17:33 2003 CET