|
|
 |
array (PHP 3, PHP 4, PHP 5 ) array --
Create an array
Descriptionarray array ( [mixed ...] )
Returns an array of the parameters. The parameters can be given
an index with the => operator. Read the section
on the array type for more
information on what an array is.
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, an 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.
Having a trailing comma after the last defined array entry, while
unusual, is a valid syntax.
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 |
<?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")
);
?>
|
|
Example 2. Automatic index with array() |
<?php
$array = array(1, 1, 1, 1, 1, 8 => 1, 4 => 1, 19, 3 => 13);
print_r($array);
?>
|
The above example will output: |
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() |
<?php
$firstquarter = array(1 => 'January', 'February', 'March');
print_r($firstquarter);
?>
|
The above example will output: Array
(
[1] => January
[2] => February
[3] => March
) |
|
As in Perl, you can access a value from the array inside double quotes.
However, with PHP you'll need to enclose your array between curly braces.
Example 4. Accessing an array inside double quotes |
<?php
$foo = array('bar' => 'baz');
echo "Hello {$foo['bar']}!"; ?>
|
|
See also array_pad(),
list(),
count(),
foreach, and
range().
User Contributed Notes
array
aissatya at yahoo dot com
16-May-2005 03:48
<?php
$foo = array('bar' => 'baz');
echo "Hello {$foo['bar']}!"; ?>
<?php
$firstquarter = array(1 => 'January', 'February', 'March');
print_r($firstquarter);
?>
<?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")
);
?>
brian at blueeye dot us
21-Apr-2005 07:34
If you need, for some reason, to create variable Multi-Dimensional Arrays, here's a quick function that will allow you to have any number of sub elements without knowing how many elements there will be ahead of time. Note that this will overwrite an existing array value of the same path.
<?php
function set_element(&$path, $data) {
return ($key = array_pop($path)) ? set_element($path, array($key=>$data)) : $data;
}
?>
For example:
<?php
echo "<pre>";
$path = array('base', 'category', 'subcategory', 'item');
$array = set_element($path, 'item_value');
print_r($array);
echo "</pre>";
?>
Will display:
Array
(
[base] => Array
(
[category] => Array
(
[subcategory] => Array
(
[item] => item_value
)
)
)
)
mortoray at ecircle-ag dot com
18-Feb-2005 07:35
Be careful if you need to use mixed types with a key of 0 in an array, as several distinct forms end up being the same key:
$a = array();
$a[null] = 1;
$a[0] = 2;
$a['0'] = 3;
$a["0"] = 4;
$a[false] = 5;
$a[0.0] = 6;
$a[''] = 7;
$a[] = 8;
print_r( $a );
This will print out only 3 values: 6, 7, 8.
rdude at fuzzelish dot com
17-Feb-2005 03:35
If you are creating an array with a large number of static items, you will find serious performance differences between using the array() function and the $array[] construct. For example:
<?
$my_array = array(1, 2, 3, … 500);
$my_array[] = 1;
$my_array[] = 2;
$my_array[] = 3;
…
$my_array[] = 500;
?>
michael dot bommarito at gmail dot com
15-Jan-2005 09:14
Just in case anyone else was looking for some help writing an LU decomposition function, here's a simple example.
N.B. All arrays are assumed to begin with index 1, not 0. This is not hard to change, but make sure you specify array(1=>...), not just array(...).
Furthermore, this function is optimized to only consider variable elements of the matrices. As $L will be a lower triangular matrix, there is no need to compute the elements of either the diagonal or the upper triangle; likewise with $U.
This function also does not check to verify that the input matrix is non-singular.
/*
* LU Decomposition
* @param $A initial matrix (1...m x 1...n)
* @param $L lower triangular matrix, passed by reference
* @param $U upper triangular matrix, passed by reference
*/
function LUDecompose($A, &$L, &$U) {
$m = sizeof($A);
$n = sizeof($A[1]);
for ( $i = 1; $i <= $m; $i++ ) {
$U[$i][$i] = $A[$i][$i];
for ( $j = $i + 1; $j <= $m; $j++ ) {
$L[$j][$i] = $A[$j][$i] / $U[$i][$i];
$U[$i][$j] = $A[$i][$j];
}
for ( $j = $i + 1; $j <= $m; $j++ ) {
for ( $k = $i + 1; $k <= $m; $k++ ) {
$A[$j][$k] = $A[$j][$k] - ($L[$j][$i] * $U[$i][$k]);
}
}
}
return;
}
phpm at nreynolds dot me dot uk
11-Jan-2005 10:24
This helper function creates a multi-dimensional array. For example, creating a three dimensional array measuring 10x20x30: <?php $my_array = multi_dim(10, 20, 30); ?>
<?php
function multi_dim()
{
$fill_value = null;
for ($arg_index = func_num_args() - 1; $arg_index >= 0; $arg_index--) {
$dim_size = func_get_arg($arg_index);
$fill_value = array_fill(0, $dim_size, $fill_value);
}
return $fill_value;
}
?>
stephen[AT]brooksie-net[DOT]co[DOT]uk
17-Dec-2004 06:57
I think I may have found a simpler, slightly more logical route to solving the previous problem. I came across this solution when retreving data from MySql which in most cases was for individual bits of data, but also needed to reference a set of sub data from a second table.
<?php
function db_get_data()
{
$ar_sub = array();
$row = mysql_fetch_row($result);
$ar_details['item0'] = $row ['field0'];
$ar_details['item1'] = $row ['field1'];
while($row_sub = mysql_fetch_array($result_sub))
{
array_push($ar_sub, $row_sub['sub_field']);
}
$ar_details['item3'] = $ar_sub;
return $ar_details;
}
$arr_details = db_get_data()
echo $ar_details['item1'];
echo $ar_details['item2'];
for($i=0; $i<count($ar_details['item3']); $i++)
{
echo $ar_details['item3'][$i];
}
?>
For extra sub tables the process can be repeated by adding more sub arrays, and each sub array can hold as much data as you like. Therefore allowing you to build an ever expanding tree as required. If you have the option I would recommend using nested classes though :)
baZz
16-Oct-2003 05:27
Chek this out!!!. Suppose that you want to create an array like the following:
<?php
$arr1 = (
0 => array ("customer"=>"Client 1","Item a"),
1 => array ("customer"=>"Client 2","Item b")
);
?>
Seems prety easy, but what if you want to generate it dinamically woops!!!. Imagine that you have a file with thousands of lines and each line is a purchase order from diferent clients:
<?php
function addArray(&$array, $id, $var)
{
$tempArray = array( $var => $id);
$array = array_merge ($array, $tempArray);
}
function addArrayArr(&$array, $var, &$array1)
{
$tempArray = array($var => $array1);
$array = array_merge ($array, $tempArray);
}
$keyarr = array("customer","item");
$valarr0 = array("Client 1","Item a");
$valarr1 = array("Client 2","Item b");
$numofrows = 2;$tmpArray = array();
for($i = 0; $i < $numofrows; $i++){
$tmp = "valarr$i";
$tmpvar = ${$tmp};foreach( $keyarr as $key=>$value){
addArray($tmparr,$tmpvar[$key],$value);
}
addArrayArr($finalarr,$i,$tmparr);
} echo "Customer: ".$finalarr[0]["customer"]."<br>";
echo "Item: ".$finalarr[0]["item"]."<br>";
echo "Customer: ".$finalarr[1]["customer"]."<br>";
echo "Item: ".$finalarr[1]["item"]."<br>";
?>
The lines above should print something like:
Customer: Client 1
Item: Item a
Customer: Client 2
Item: Item b
I hope someone find this useful.
TCross1 at hotmail dot com
03-Sep-2003 02:38
here is the sort of "textbook" way to output the contents of an array which avoids using foreach() and allows you to index & iterate through the array as you see fit:
<?php
$arrayName = array("apples", "bananas", "oranges", "pears");
$arrayLength = count($arrayName);
for ($i = 0; $i < $arrayLength; $i++){
echo "arrayName at[" . $i . "] is: [" .$arrayName[$i] . "]<br>\n";
}
?>
enjoy!
-tim
darthjarkon at hotmail dot com
09-Jul-2003 01:09
I found a slightly better way to create large 2d arrays:
<?php
function display_all($array){
echo "<table><tr>";
foreach($array as $spot){
echo "<td align='center' width= '20'>";
foreach($spot as $spotdeux){
echo "<br>".$spotdeux;
}
}
echo "</tr> </table>";
}
function creater_array(){
$ar=Array();
$xax=5;
$yax=5;
$i=1;
for ($y=0; $y<$yax; $y++)
{
array_push($ar,array());
for ($x=0; $x<$xax; $x++)
{
array_push($ar[$y],"0");
}
}
return $ar;
}
$b = creater_array();
display_all($b);
?>
10-May-2003 05:53
Similarly to a comment by stlawson at sbcglobal dot net on this page:
http://www.php.net/basic-syntax.instruction-separation
It is usually advisable to define your arrays like this:
$array = array(
'foo',
'bar',
);
Note the comma after the last element - this is perfectly legal. Moreover,
it's best to add that last comma so that when you add new elements to the
array, you don't have to worry about adding a comma after what used to be
the last element.
<?php
$array = array(
'foo',
'bar',
'baz',
);
?>
marcel at labor-club dot de
24-Feb-2003 09:58
i tried to find a way to create BIG multidimensional-arrays. but the notes below only show the usage of it, or the creation of small arrays like $matrix=array('birne', 'apfel', 'beere');
for an online game, i use a big array (50x80) elements.
it's no fun, to write the declaration of it in the ordinary way.
here's my solution, to create an 2d-array, filled for example with raising numbers.
<?php
$matrix=array();
$sx=30;
$sy=40;
$i=1;
for ($y=0; $y<$sy; $y++)
{
array_push($matrix,array());
for ($x=0; $x<$sx; $x++)
{
array_push($matrix[$y],array());
$matrix[$x][$y]=$i;
$i++;
}
}
?>
if there is a better way, plz send an email. i always want to learn more php!
grubby_d at yahoo dot com
06-Dec-2002 12: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:
<?php
$myarray = array(1, 2, 3);
echo count($myarray) . "<BR>"; $myarray[NULL] = "the null value";
echo count($myarray) . "<BR>"; 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
MadLogic at Paradise dot net dot nz
31-Oct-2002 04:39
Heres a simple yet intelligent way of setting an array, grabbing the values from the array using a loop.
<?php
$ary = array("1"=>'One','Two',"3"=>'Three');
$a = '0'; $b = count($ary);
while ($a <= $b) {
$pr = $ary[$a];
print "$pr<br>";
$a++;
}
?>
mads at __nospam__westermann dot dk
23-Oct-2002 09: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:
<?php
$a = array
(
21 => 1,
2,
3,
);
print '<pre>';
print_r($a);
print '</pre>';
?>
will print:
<?php
Array
(
[21] => 1
[22] => 2
[23] => 3
)
?>
John
18-Jul-2002 01:48
Be careful not to create an array on top of an already existing variable:
<?php
$name = "John";
$name['last'] = "Doe";
?>
$name becomes "Dohn" since 'last' evaluates to the 0th position of $name.
Same is true for multi-arrays.
Markus dot Elfring at web dot de
30-May-2002 05:04
It seems to me that the use of brackets with multidimensional arrays is not described here.
But the following examples work:
<?php
$value = $point['x']['y'];
$message[1][2][3] = 'Greetings';
?>
jay at ezlasvegas dot net
20-Apr-2002 06: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
jjm152 at hotmail dot com
10-Mar-2002 08: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:
<?php
$arr = array( 1, 2, 3, 4, 5 );
foreach ( $arr as $val ) {
echo "Value: $Val\n";
}
?>
For multi dim array:
<?php
$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.
tobiasquinteiro at ig dot com dot br
29-Jan-2002 02:25
<?
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";
}
?>
deepak_pradhan at yahoo dot com
15-Sep-2001 07: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
joshua dot e at usa dot net
24-May-2001 01: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:
<?php
$sql = "SELECT key,value FROM table";
$result = mysql_query($sql);
while($row = mysql_fetch_row($result)) {
$myArray[$row[0]] = $row[1];
}
while(list($key,$value) = each($myArray)) {
echo "$key : $value";
}
?>
I found this to be super efficient, and extremely cool.
xftp at yahoo dot com
21-May-2001 10: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";
?>
slicky at newshelix dot com
20-Mar-2001 03: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:
<?php
foreach ($lines as $line){
if(!trim($line)) continue;
$tds[] = explode("$delimiter",$line);
}
?>
jasonr at argia dot net
27-Nov-2000 07: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.
rubein at earthlink dot net
26-Sep-2000 01: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
php-manual at improbable dot org
02-Apr-2000 05: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);
baghera at mindspring dot com
12-Oct-1999 04: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.
| |