array

(PHP 4, PHP 5, PHP 7, PHP 8)

arrayCrea un array

Descripción

array(mixed $... = ?): array

Crea un array. Leer la sección el tipo array para más información sobre que es un array.

Parámetros

...

Sintaxis "índice => valores", separados por comas, define índice y valores. El índice puede ser de tipo cadena o numérico. Cuando se omite el índice, se genera un índice numérico automáticamente, empezando por 0. Si el índice es numérico, el siguiente índice generado será el número del índice mayor +1. Nótese que cuando se crean dos índices idénticos, el último sobrescribe el primero.

Tener una coma al final de la última entrada definida en el array, aunque no es usual, sigue siendo sintaxis válida.

Valores devueltos

Devuelve un array de parámetros. Los parámetros puede ser devolver un índice con el operador =>. Leer la sección en El tipo array para más información en que es un array.

Ejemplos

El siguiente ejemplo demuestra como crear un array de dos dimensiones, como especificar claves para un array asociativo y como omitir y continuar índices numéricos en array normales.

Ejemplo #1 Ejemplo de array()

<?php
$fruits
= array (
"frutas" => array("a" => "naranja", "b" => "plátano", "c" => "manzana"),
"números" => array(1, 2, 3, 4, 5, 6),
"hoyos" => array("primero", 5 => "segundo", "tercero")
);
?>

Ejemplo #2 Array() con índice automático

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

El resultado del ejemplo sería:

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

Nótese que el índice '3' se ha definido en dos ocasiones y mantiene su valor final de 13. El índice 4 se ha definido después del índice 8 y el siguiente índice generado (valor 19) es 9, ya que el índice mayor era 8.

Este ejemplo crea un array de base 1.

Ejemplo #3 array() con índice de base 1

<?php
$firstquarter
= array(1 => 'Enero', 'Febrero', 'Marzo');
print_r($firstquarter);
?>

El resultado del ejemplo sería:

Array
(
    [1] => Enero
    [2] => Febrero
    [3] => Marzo
)

Como en perl, se puede acceder al valor del array dentro de comillas dobles. Sin embargo, con PHP se necesita adjuntar el array enter claves.

Ejemplo #4 Accessing an array inside double quotes

<?php

$foo
= array('bar' => 'baz');
echo
"Hola {$foo['bar']}!"; // Hola baz!

?>

Notas

Nota:

array() es un constructor de lenguaje para representar arrays y no es una función.

Ver también

  • array_pad() - Rellena un array a la longitud especificada con un valor
  • list() - Asignar variables como si fueran un array
  • count() - Cuenta todos los elementos de un array o algo de un objeto
  • range() - Crear un array que contiene un rango de elementos
  • foreach
  • El tipo array

add a note

User Contributed Notes 17 notes

up
116
ole dot aanensen at gmail dot com
10 years ago
As of PHP 5.4.x you can now use 'short syntax arrays' which eliminates the need of this function.

Example #1 'short syntax array'
<?php
$a
= [1, 2, 3, 4];
print_r($a);
?>

The above example will output:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)

Example #2 'short syntax associative array'
<?php
$a
= ['one' => 1, 'two' => 2, 'three' => 3, 'four' => 4];
print_r($a);
?>

The above example will output:
Array
(
[one] => 1
[two] => 2
[three] => 3
[four] => 4
)
up
3
jon hohle
16 years ago
Here are shorter versions of sam barrow's functions. From a PHP perspective these are O(1) (without getting into what's going on in the interpreter), instead of O(n).

<?php
function randomKey(array $array)
{
return
randomElement(array_keys($array));
}

function
randomElement(array $array)
{
if (
count($array) === 0)
{
trigger_error('Array is empty.', E_USER_WARNING);
return
null;
}

$rand = mt_rand(0, count($array) - 1);
$array_keys = array_keys($array);

return
$array[$array_keys[$rand]];
}
?>
up
1
jupiter at nospam dot com
18 years ago
<?php

// changes any combination of multiarray elements and subarrays
// into a consistent 2nd level multiarray, tries to preserves keys
function changeMultiarrayStructure($multiarray, $asc = 1) {
if (
$asc == 1) { // use first subarrays for new keys of arrays
$multiarraykeys = array_reverse($multiarray, true);
} else {
// use the last array keys
$multiarraykeys = $multiarray; // use last subarray keys
} // end array reordering
$newarraykeys = array(); // establish array
foreach ($multiarraykeys as $arrayvalue) { // build new array keys
if (is_array($arrayvalue)) { // is subarray an array
$newarraykeys = array_keys($arrayvalue) + $newarraykeys;
}
// if count(prevsubarray)>count(currentarray), extras survive
} // end key building loop
foreach ($multiarray as $newsubarraykey => $arrayvalue) {
if (
is_array($arrayvalue)) { // multiarray element is an array
$i = 0; // start counter for subarray key
foreach ($arrayvalue as $subarrayvalue) { // access subarray
$newmultiarray[$newarraykeys[$i]][$newsubarraykey] = $subarrayvalue;
$i++; // increase counter
} // end subarray loop
} else { // multiarray element is a value
foreach ($newarraykeys as $newarraykey) { // new subarray keys
$newmultiarray[$newarraykey][$newsubarraykey] = $arrayvalue;
}
// end loop for array variables
} // end conditional
} // end new multiarray building loop
return $newmultiarray;
}

// will change
$old = array('a'=>1,'b'=>array('e'=>2,'f'=>3),'c'=>array('g'=>4),'d'=>5);
// to
$new = array('e'=>array('a'=>1,'b'=>2,'c'=>4,'d'=>5),
'f'=>array('a'=>1,'b'=>3,'d'=>5));

// note: if $asc parameter isn't default, last subarray keys used

?>

The new key/value assignment pattern is clearer with bigger arrays.
I use this to manipulate input/output data from my db. Enjoy.
up
0
Marcel G
15 years ago
I encountered the following but didn't see it documented/reported anywhere so I'll just mentioned it here.

As written in the manual:
"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".

This generated index has always the largest integer used as a key so far. So adding $a[5] = 'foo'; after an $a[10] = 'bar'; will not force the next generated index to be 6 but to be 11 as 10 was the highest index encountered until here.

Anyway, the following can happen:
<?php
$max_int
= 2147483647; // Max value for integer on a 32-bit system
$arr = array();

$arr[1] = 'foo'; // New generated index will be 2
$arr[ $max_int ] = 'bar'; // Caution: Next generated index will be -2147483648 due to the integer overflow!
$arr[0] = 'bar'; // The highest value should be 2147483648 but due to the i-overflow it is -2147483648 so current index 0 is larger. The new generated index therefore is 1!
$arr[] = 'failure'; // Warning: Cannot add element to the array as the next element is already occupied.
?>
up
0
jonberglund at gmail dot com
16 years ago
The following function (similar to one above) will render an array as a series of HTML select options (i.e. "<option>...</option>"). The problem with the one before is that there was no way to handle <optgroup>, so this function solves that issue.

function arrayToSelect($option, $selected = '', $optgroup = NULL)
{
$returnStatement = '';

if ($selected == '') {
$returnStatement .= '<option value="" selected="selected">Select one...</option>';
}

if (isset($optgroup)) {
foreach ($optgroup as $optgroupKey => $optgroupValue) {
$returnStatement .= '<optgroup label="' . $optgroupValue . '">';

foreach ($option[$optgroupKey] as $optionKey => $optionValue) {
if ($optionKey == $selected) {
$returnStatement .= '<option selected="selected" value="' . $optionKey . '">' . $optionValue . '</option>';
} else {
$returnStatement .= '<option value="' . $optionKey . '">' . $optionValue . '</option>';
}
}

$returnStatement .= '</optgroup>';
}
} else {
foreach ($option as $key => $value) {
if ($key == $selected) {
$returnStatement .= '<option selected="selected" value="' . $key . '">' . $value . '</option>';
} else {
$returnStatement .= '<option value="' . $key . '">' . $value . '</option>';
}
}
}

return $returnStatement;
}

So, for example, I needed to render a list of states/provinces for various countries in a select field, and I wanted to use each country name as an <optgroup> label. So, with this function, if only a single array is passed to the function (i.e. "arrayToSelect($stateList)") then it will simply spit out a bunch of "<option>" elements. On the other hand, if two arrays are passed to it, the second array becomes a "key" for translating the first array.

Here's a further example:

$countryList = array(
'CA' => 'Canada',
'US' => 'United States');

$stateList['CA'] = array(
'AB' => 'Alberta',
'BC' => 'British Columbia',
'AB' => 'Alberta',
'BC' => 'British Columbia',
'MB' => 'Manitoba',
'NB' => 'New Brunswick',
'NL' => 'Newfoundland/Labrador',
'NS' => 'Nova Scotia',
'NT' => 'Northwest Territories',
'NU' => 'Nunavut',
'ON' => 'Ontario',
'PE' => 'Prince Edward Island',
'QC' => 'Quebec',
'SK' => 'Saskatchewan',
'YT' => 'Yukon');

$stateList['US'] = array(
'AL' => 'Alabama',
'AK' => 'Alaska',
'AZ' => 'Arizona',
'AR' => 'Arkansas',
'CA' => 'California',
'CO' => 'Colorado',
'CT' => 'Connecticut',
'DE' => 'Delaware',
'DC' => 'District of Columbia',
'FL' => 'Florida',
'GA' => 'Georgia',
'HI' => 'Hawaii',
'ID' => 'Idaho',
'IL' => 'Illinois',
'IN' => 'Indiana',
'IA' => 'Iowa',
'KS' => 'Kansas',
'KY' => 'Kentucky',
'LA' => 'Louisiana',
'ME' => 'Maine',
'MD' => 'Maryland',
'MA' => 'Massachusetts',
'MI' => 'Michigan',
'MN' => 'Minnesota',
'MS' => 'Mississippi',
'MO' => 'Missouri',
'MT' => 'Montana',
'NE' => 'Nebraska',
'NV' => 'Nevada',
'NH' => 'New Hampshire',
'NJ' => 'New Jersey',
'NM' => 'New Mexico',
'NY' => 'New York',
'NC' => 'North Carolina',
'ND' => 'North Dakota',
'OH' => 'Ohio',
'OK' => 'Oklahoma',
'OR' => 'Oregon',
'PA' => 'Pennsylvania',
'RI' => 'Rhode Island',
'SC' => 'South Carolina',
'SD' => 'South Dakota',
'TN' => 'Tennessee',
'TX' => 'Texas',
'UT' => 'Utah',
'VT' => 'Vermont',
'VA' => 'Virginia',
'WA' => 'Washington',
'WV' => 'West Virginia',
'WI' => 'Wisconsin',
'WY' => 'Wyoming');

...

<select name="state" id="state"><?php echo arrayToSelect($stateList,'',$countryList) ?></select>
<select name="country" id="country"><?php echo arrayToSelect($countryList,'US') ?></select>
up
-1
Mike Mackintosh
16 years ago
If you need to add an object as an array key, for example an object from Simple XML Parser, you can use the following.

File.XML
<?xml version="1.0" encoding="UTF-8"?>
<Settings type="General">
<Setting name="SettingName">This This This</Setting>
</Settings>

The script:
<?php
$raw
= $xml = new SimpleXMLElement('File.XML');
foreach(
$raw->Setting as $A => $B)
{
// Set Array From XML
$Setting[(string) $B['name']] = (string) $B[0];
}
?>
By telling the key to read the object as a string, it will let you set it.

Hope this helps someone out!
up
-2
razvan_bc at yahoo dot com
4 years ago
an array can execute code.
i try this on php 7.4 (xampp version)

<?php

[
$msg='HI GUYS !'
,print ($msg)
,(function()use (
$msg){
print
'here is php';
})()
,print
' I`m just an array ,alive one'
];

?>
up
-2
slicky at newshelix dot com
23 years ago
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);
}
?>
up
-5
brian at blueeye dot us
19 years ago
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
// set_element(array path, mixed value)
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
)
)
)
)
up
-2
jjm152 at hotmail dot com
22 years ago
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.
up
-4
rubein at earthlink dot net
24 years ago
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
up
-4
bill at carneyco dot com
18 years ago
I wanted to be able to control the flow of data in a loop instead of just building tables with it or having to write 500 select statements for single line items. This is what I came up with thanks to the help of my PHP brother in FL. Hope someone else gets some use out it.
<?

//set array variable
$results = array();

//talk to the db
$query = "SELECT * FROM yourtable";
$result = mysql_query($query) or die(mysql_error());

//count the rows and fields
$totalRows = mysql_num_rows($result);
$totalFields = mysql_num_fields($result);

//start the loop
for ( $i = 0; $i < $totalRows; ++$i ) {

//make it 2 dim in case you change your order
$results[$i] = mysql_fetch_array($result);

//call data at will controlling the loop with the array
echo $results[your_row_id]['your_field_name']; }

//print the entire array to see what lives where
print_r($results); ?>
up
-3
Anonymous
21 years ago
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',
);
?>
up
-5
php
18 years ago
This function converts chunks of a string in an array:

function array_str($str, $len) {
$newstr = '';
for($i = 0; $i < strlen($str); $i++) {
$newstr .= substr($str, $i, $len);
}
return $newstr;
}

use it as:

$str = "abcdefghilmn";
echo "<table width=\"100%\">\n";
foreach(array_str($str, 4) as $chunk) {
echo "<tr><td>".$chunk."</td></tr>\n";
}
echo "</table>";

this prints:

------
abcd
------
efgh
------
ilmn
------

It don't use regular expressions. Please add this function to php :)
up
-5
rdude at fuzzelish dot com
19 years ago
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:
<?
// Slower method
$my_array = array(1, 2, 3, ? 500);

// Faster method
$my_array[] = 1;
$my_array[] = 2;
$my_array[] = 3;
?
$my_array[] = 500;
?>
up
-4
jay at ezlasvegas dot net
22 years ago
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
up
-5
mads at __nospam__westermann dot dk
21 years ago
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
)
?>
To Top