Arrays

Un array en PHP es en realidad un mapa ordenado. Un mapa es un tipo de datos que asocia valores con claves. Este tipo se optimiza para varios usos diferentes; se puede emplear como un array, lista (vector), tabla asociativa (tabla hash - una implementación de un mapa), diccionario, colección, pila, cola, y posiblemente más. Ya que los valores de un array pueden ser otros arrays, también son posibles árboles y arrays multidimensionales.

Una explicación sobre tales estructuras de datos está fuera del alcance de este manual, aunque se proporciona al menos un ejemplo de cada uno de ellos. Para más información, consulte la extensa literatura que existe sobre este amplio tema.

Sintaxis

Especificación con array()

Un array puede ser creado con el constructor del lenguaje array(). Éste toma cualquier número de parejas clave => valor como argumentos.

    array(
    clave  => valor,
    clave2 => valor2,
    clave3 => valor3,
    ...
    )

La coma después del último elemento del array es opcional, pudiéndose omitir. Esto normalmente se hace para arrays de una única línea, es decir, es preferible array(1, 2) que array(1, 2, ). Por otra parte, para arrays multilínea, la coma final se usa frecuentemente, ya que permite una adición más sencilla de nuevos elementos al final.

A partir de PHP 5.4 también se puede usar la sintaxis de array corta, la cual reemplaza array() con [].

Ejemplo #1 Un array simple

<?php
$array 
= array(
    
"foo" => "bar",
    
"bar" => "foo",
);

// a partir de PHP 5.4
$array = [
    
"foo" => "bar",
    
"bar" => "foo",
];
?>

La clave puede ser un integer o un string. El valor puede ser de cualquier tipo.

Además, se darán los siguientes amoldamientos de clave:

  • Strings que contiene un decimal válido integer, a menos que el número esté precedido por un signo +, será amoldado al tipo integer. Por ejemplo, la llave "8" será en realidad almacenado como 8. Por otro lado "08" no será moldeado, ya que no es un entero decimal válido.
  • Un floats también será amoldado a integer, lo que significa que la parte fraccionaria se elimina. P.ej., la clave 8.7 en realidad será almacenada como 8.
  • Un booleano son amoldados a integers también, es decir, la clave true en realidad será almacenada como 1 y la clave false como 0.
  • Un null será amoldado a un string vacío, es decir, la clave null en realidad será almacenada como "".
  • Los arrays y los objects no pueden utilizarse como claves. Si se hace, dará lugar a una advertencia: Illegal offset type.

Si varios elementos en la declaración del array usan la misma clave, sólo se utilizará la última, siendo los demás sobrescritos.

Ejemplo #2 Ejemplo de amoldamiento de tipo y sobrescritura

<?php
$array 
= array(
    
1    => "a",
    
"1"  => "b",
    
1.5  => "c",
    
true => "d",
);
var_dump($array);
?>

El resultado del ejemplo sería:

array(1) {
  [1]=>
  string(1) "d"
}

Como todas las claves en el ejemplo anterior se convierten en 1, los valores serán sobrescritos en cada nuevo elemento, por lo que el último valor asignado "d" es el único que queda.

Los arrays de PHP pueden contener claves integer y string al mismo tiempo ya que PHP no distingue entre arrays indexados y asociativos.

Ejemplo #3 Claves mixtas integer y string

<?php
$array 
= array(
    
"foo" => "bar",
    
"bar" => "foo",
    
100   => -100,
    -
100  => 100,
);
var_dump($array);
?>

El resultado del ejemplo sería:

array(4) {
  ["foo"]=>
  string(3) "bar"
  ["bar"]=>
  string(3) "foo"
  [100]=>
  int(-100)
  [-100]=>
  int(100)
}

La clave es opcional. Si no se especifica, PHP usará el incremento de la clave de tipo integer mayor utilizada anteriormente.

Ejemplo #4 Arrays indexados sin clave

<?php
$array 
= array("foo""bar""hello""world");
var_dump($array);
?>

El resultado del ejemplo sería:

array(4) {
  [0]=>
  string(3) "foo"
  [1]=>
  string(3) "bar"
  [2]=>
  string(5) "hello"
  [3]=>
  string(5) "world"
}

Es posible especificar la clave sólo para algunos elementos y excluir a los demás:

Ejemplo #5 Claves no en todos los elementos

<?php
$array 
= array(
         
"a",
         
"b",
    
=> "c",
         
"d",
);
var_dump($array);
?>

El resultado del ejemplo sería:

array(4) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [6]=>
  string(1) "c"
  [7]=>
  string(1) "d"
}

Como se puede ver, al último valor "d" se le asignó la clave 7. Esto es debido a que la mayor clave integer anterior era 6.

Acceso a elementos de array con la sintaxis de corchete

Los elementos de array se pueden acceder utilizando la sintaxis array[key].

Ejemplo #6 Acceso a elementos de un array

<?php
$array 
= array(
    
"foo" => "bar",
    
42    => 24,
    
"multi" => array(
         
"dimensional" => array(
             
"array" => "foo"
         
)
    )
);

var_dump($array["foo"]);
var_dump($array[42]);
var_dump($array["multi"]["dimensional"]["array"]);
?>

El resultado del ejemplo sería:

string(3) "bar"
int(24)
string(3) "foo"

Nota:

Tanto los corchetes como las llaves pueden ser utilizados de forma intercambiable para acceder a los elementos de un array (p.ej.: $array[42] y $array{42} tendrán el mismo resultado en el ejemplo anterior).

A partir de PHP 5.4 es posible hacer referencia al array del resultado de una llamada a una función o método directamente. Antes sólo era posible utilizando una variable temporal.

Desde PHP 5.5 es posible hacer referencia directa un elemento de un array literal.

Ejemplo #7 Hacer referencia al resultado array de funciones

<?php
function getArray() {
    return array(
123);
}

// en PHP 5.4
$secondElement getArray()[1];

// anteriormente
$tmp getArray();
$secondElement $tmp[1];

// o
list(, $secondElement) = getArray();
?>

Nota:

Intentar acceder a una clave de un array que no se ha definido es lo mismo que el acceder a cualquier otra variable no definida: se emitirá un mensaje de error de nivel E_NOTICE, y el resultado será null.

Nota:

Array que dereferencia un valor escalar que no es un string silenciosamente arroja null, es decir, sin emitir un mensaje de error.

Creación/modificación con la sintaxis de corchete

Un array existente puede ser modificado estableciendo explícitamente valores en él.

Esto se realiza asignando valores al array, especificando la clave entre corchetes. Esta también se puede omitir, resultando en un par de corchetes vacíos ([]).

    $arr[clave] = valor;
    $arr[] = valor;
    // clave puede ser un integer o un string
    // valor puede ser cualquier valor de cualquier tipo

Si $arr aún no existe, se creará, siendo también esta forma una alternativa de crear un array. Sin embargo, se desaconsejada esta práctica porque que si $arr ya contiene algún valor (p.ej. un string de una variable de petición), este estará en su lugar y [] puede significar realmente el operador de acceso a strings. Siempre es mejor inicializar variables mediante una asignación directa.

Nota: A partir de PHP 7.1.0, la aplicación del operador de índice vacío en un string lanza un fatal error. Antes, el string se convertía silenciosamente en un array.

Para cambiar un valor determinado se debe asignar un nuevo valor a ese elemento empleando su clave. Para quitar una pareja clave/valor, se debe llamar a la función unset() con éste.

<?php
$arr 
= array(=> 112 => 2);

$arr[] = 56;    // Esto es lo mismo que $arr[13] = 56;
                // en este punto de el script

$arr["x"] = 42// Esto agrega un nuevo elemento a
                // el array con la clave "x"
                
unset($arr[5]); // Esto elimina el elemento del array

unset($arr);    // Esto elimina el array completo
?>

Nota:

Como se mencionó anteriormente, si no se especifica una clave, se toma el máximo de los índices integer existentes, y la nueva clave será ese valor máximo más 1 (aunque al menos 0). Si todavía no existen índices integer, la clave será 0 (cero).

Tenga en cuenta que la clave integer máxima utilizada para éste no es necesario que actualmente exista en el array. Ésta sólo debe haber existido en el array en algún momento desde la última vez que el array fué re-indexado. El siguiente ejemplo ilustra este comportamiento:

<?php
// Crear un array simple.
$array = array(12345);
print_r($array);

// Ahora elimina cada elemento, pero deja el mismo array intacto:
foreach ($array as $i => $value) {
    unset(
$array[$i]);
}
print_r($array);

// Agregar un elemento (note que la nueva clave es 5, en lugar de 0).
$array[] = 6;
print_r($array);

// Re-indexar:
$array array_values($array);
$array[] = 7;
print_r($array);
?>

El resultado del ejemplo sería:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
Array
(
)
Array
(
    [5] => 6
)
Array
(
    [0] => 6
    [1] => 7
)

Funciones útiles

Hay un buen número de funciones útiles para trabajar con arrays. Véase la sección funciones de array.

Nota:

La función unset() permite remover claves de un array. Tenga en cuenta que el array no es re-indexado. Si se desea un verdadero comportamiento "eliminar y desplazar", el array puede ser re-indexado usando la función array_values().

<?php
$a 
= array(=> 'uno'=> 'dos'=> 'tres');
unset(
$a[2]);
/* producirá un array que se ha definido como
   $a = array(1 => 'uno', 3 => 'tres');
   y NO
   $a = array(1 => 'uno', 2 =>'tres');
*/

$b array_values($a);
// Ahora $b es array(0 => 'uno', 1 =>'tres')
?>

La estructura de control foreach existe específicamente para arrays. Ésta provee una manera fácil de recorrer un array.

Recomendaciones sobre arrays y cosas a evitar

¿Por qué es incorrecto $foo[bar]?

Siempre deben usarse comillas alrededor de un índice de array tipo string literal. Por ejemplo, $foo['bar'] es correcto, mientras que $foo[bar] no lo es. ¿Pero por qué? Es común encontrar este tipo de sintaxis en scripts viejos:

<?php
$foo
[bar] = 'enemy';
echo 
$foo[bar];
// etc
?>

Esto está mal, pero funciona. La razón es que este código tiene una constante indefinida (bar) en lugar de un string ('bar' - observe las comillas). Funciona porque PHP automáticamente convierte un string puro (un string sin comillas que no corresponde con ningún símbolo conocido) en un string que contiene el string puro. Por ejemplo, si no se ha definido una constante llamada bar, entonces PHP reemplazará su valor por el string 'bar' y usará éste último.

Advertencia

La alternativa de tratar una constante indefinida como string vacío está obsoleto a partir de PHP 7.2.0, y emite un error de nivel E_WARNING. Anteriormente, un error de nivel E_NOTICE era emitido.

Nota: Esto no quiere decir que siempre haya que usar comillas en la clave. No use comillas con claves que sean constantes o variables, ya que en tal caso PHP no podrá interpretar sus valores.

<?php
error_reporting
(E_ALL);
ini_set('display_errors'true);
ini_set('html_errors'false);
// Array simple:
$array = array(12);
$count count($array);
for (
$i 0$i $count$i++) {
    echo 
"\nRevisando $i: \n";
    echo 
"Mal: " $array['$i'] . "\n";
    echo 
"Bien: " $array[$i] . "\n";
    echo 
"Mal: {$array['$i']}\n";
    echo 
"Bien: {$array[$i]}\n";
}
?>

El resultado del ejemplo sería:

Revisando 0:
Notice: Undefined index:  $i in /path/to/script.html on line 9
Mal:
Bien: 1
Notice: Undefined index:  $i in /path/to/script.html on line 11
Mal:
Bien: 1

Revisando 1:
Notice: Undefined index:  $i in /path/to/script.html on line 9
Mal:
Bien: 2
Notice: Undefined index:  $i in /path/to/script.html on line 11
Mal:
Bien: 2

Más ejemplos para demostrar este comportamiento:

<?php
// Mostrar todos los errores
error_reporting(E_ALL);

$arr = array('fruit' => 'apple''veggie' => 'carrot');

// Correcto
print $arr['fruit'];  // apple
print $arr['veggie']; // carrot

// Incorrecto. Esto funciona pero también genera un error de PHP de
// nivel E_NOTICE ya que no hay definida una constante llamada fruit
//
// Notice: Use of undefined constant fruit - assumed 'fruit' in...
print $arr[fruit];    // apple

// Esto define una constante para demostrar lo que pasa. El valor 'veggie'
// es asignado a una constante llamada fruit.
define('fruit''veggie');

// Note la diferencia ahora
print $arr['fruit'];  // apple
print $arr[fruit];    // carrot

// Lo siguiente está bien ya que se encuentra al interior de una cadena. Las constantes no son procesadas al 
// interior de cadenas, así que no se produce un error E_NOTICE aquí
print "Hello $arr[fruit]";      // Hello apple

// Con una excepción, los corchetes que rodean las matrices al
// interior de cadenas permiten el uso de constantes
print "Hello {$arr[fruit]}";    // Hello carrot
print "Hello {$arr['fruit']}";  // Hello apple

// Esto no funciona, resulta en un error de intérprete como:
// Parse error: parse error, expecting T_STRING' or T_VARIABLE' or T_NUM_STRING'
// Esto por supuesto se aplica también al uso de superglobales en cadenas
print "Hello $arr['fruit']";
print 
"Hello $_GET['foo']";

// La concatenación es otra opción
print "Hello " $arr['fruit']; // Hello apple
?>

Cuando se habilita error_reporting para mostrar errores de nivel E_NOTICE (como por ejemplo definiendo el valor E_ALL), este tipo de usos serán inmediatamente visibles. Por omisión, error_reporting se encuentra configurado para no mostrarlos.

Tal y como se indica en la sección de sintaxis, lo que existe entre los corchetes cuadrados ('[' y ']') debe ser una expresión. Esto quiere decir que código como el siguiente funciona:

<?php
echo $arr[somefunc($bar)];
?>

Este es un ejemplo del uso de un valor devuelto por una función como índice del array. PHP también conoce las constantes:

<?php
$error_descriptions
[E_ERROR]   = "Un error fatal ha ocurrido";
$error_descriptions[E_WARNING] = "PHP produjo una advertencia";
$error_descriptions[E_NOTICE]  = "Esta es una noticia informal";
?>

Note que E_ERROR es también un identificador válido, asi como bar en el primer ejemplo. Pero el último ejemplo es equivalente a escribir:

<?php
$error_descriptions
[1] = "Un error fatal ha ocurrido";
$error_descriptions[2] = "PHP produjo una advertencia";
$error_descriptions[8] = "Esta es una noticia informal";
?>

ya que E_ERROR es igual a 1, etc.

¿Entonces porqué está mal?

En algún momento en el futuro, puede que el equipo de PHP quiera usar otra constante o palabra clave, o una constante proveniente de otro código puede interferir. Por ejemplo, en este momento no puede usar las palabras empty y default de esta forma, ya que son palabras clave reservadas.

Nota: Reiterando, al interior de un valor string entre comillas dobles, es válido no rodear los índices de array con comillas, así que "$foo[bar]" es válido. Consulte los ejemplos anteriores para más detalles sobre el porqué, así como la sección sobre procesamiento de variables en cadenas.

Conversión a array

Para cualquiera de los tipos integer, float, string, boolean y resource, convertir un valor a un array resulta en un array con un solo elemento, con índice 0, y el valor del escalar que fue convertido. En otras palabras, (array)$scalarValue es exactamente lo mismo que array($scalarValue).

Si convierte un object a un array, el resultado es un array cuyos elementos son las propiedades del object. Las claves son los nombres de las variables miembro, con algunas excepciones notables: las variables privadas tienen el nombre de la clase al comienzo del nombre de la variable; las variables protegidas tienen un caracter '*' al comienzo del nombre de la variable. Estos valores adicionados al inicio tienen bytes nulos a los lados. Esto puede resultar en algunos comportamientos inesperados:

<?php

class {
    private 
$A//  Este campo se convertirá en '\0A\0A'
}

class 
extends {
    private 
$A// Este campo se convertirá en '\0B\0A'
    
public $AA// Este campo se convertirá en 'AA'
}

var_dump((array) new B());
?>

En el ejemplo anterior parecerá que se tienen dos claves llamadas 'AA', aunque en realidad una de ellas se llama '\0A\0A'.

Si convierte un valor null a array, obtiene un array vacío.

Comparación

Es posible comparar arrays con la función array_diff() y mediante operadores de arrays.

Ejemplos

El tipo array en PHP es bastante versátil. Aquí hay algunos ejempos:

<?php
// Esto:
$a = array( 'color' => 'red',
            
'taste' => 'sweet',
            
'shape' => 'round',
            
'name'  => 'apple',
            
4        // la clave será 0
          
);

$b = array('a''b''c');

// . . .es completamente equivalente a
$a = array();
$a['color'] = 'red';
$a['taste'] = 'sweet';
$a['shape'] = 'round';
$a['name']  = 'apple';
$a[]        = 4;        // la clave será 0

$b = array();
$b[] = 'a';
$b[] = 'b';
$b[] = 'c';

// Después de que se ejecute el código, $a será el array
// array('color' => 'red', 'taste' => 'sweet', 'shape' => 'round',
// 'name' => 'apple', 0 => 4), y $b será el array
// array(0 => 'a', 1 => 'b', 2 => 'c'), o simplemente array('a', 'b', 'c').
?>

Ejemplo #8 Uso de array()

<?php
// Array como mapa de propiedades
$map = array( 'version'    => 4,
              
'OS'         => 'Linux',
              
'lang'       => 'english',
              
'short_tags' => true
            
);
            
// Keys estrictamente numéricas
$array = array( 7,
                
8,
                
0,
                
156,
                -
10
              
);
// esto es lo mismo que array(0 => 7, 1 => 8, ...)

$switching = array(         10// key = 0
                    
5    =>  6,
                    
3    =>  7,
                    
'a'  =>  4,
                            
11// key = 6 (el índice entero máximo era 5)
                    
'8'  =>  2// key = 8 (integer!)
                    
'02' => 77// key = '02'
                    
0    => 12  // el valor 10 será reemplazado por 12
                  
);
                  
// array vacío
$empty = array();         
?>

Ejemplo #9 Colección

<?php
$colors 
= array('rojo''azul''verde''amarillo');

foreach (
$colors as $color) {
    echo 
"¿Le gusta el $color?\n";
}

?>

El resultado del ejemplo sería:

¿Le gusta el rojo?
¿Le gusta el azul?
¿Le gusta el verde?
¿Le gusta el amarillo?

Modificar los valores del array directamente es posible pasándolos por referencia.

Ejemplo #10 Cambiando elemento en el bucle

<?php
foreach ($colors as &$color) {
    
$color strtoupper($color);
}
unset(
$color); /* se asegura de que escrituras subsiguientes a $color
no modifiquen el último elemento del arrays */

print_r($colors);
?>

El resultado del ejemplo sería:

Array
(
    [0] => ROJO
    [1] => AZUL
    [2] => VERDE
    [3] => AMARILLO
)

Este ejemplo crea un array con base uno.

Ejemplo #11 Índice con base 1

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

El resultado del ejemplo sería:

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

Ejemplo #12 Llenado de un array

<?php
// llenar un array con todos los ítems de un directorio
$handle opendir('.');
while (
false !== ($file readdir($handle))) {
    
$files[] = $file;
}
closedir($handle);
?>

Los Arrays son ordenados. El orden puede ser modificado usando varias funciones de ordenado. Vea la sección sobre funciones de arrays para más información. La función count() puede ser usada para contar el número de elementos en un array.

Ejemplo #13 Ordenado de un array

<?php
sort
($files);
print_r($files);
?>

Dado que el valor de un array puede ser cualquier cosa, también puede ser otro array. De esta forma es posible crear arrays recursivas y multi-dimensionales.

Ejemplo #14 Arrays recursivos y multi-dimensionales

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

// Algunos ejemplos que hacen referencia a los valores del array anterior
echo $fruits["holes"][5];    // prints "second"
echo $fruits["fruits"]["a"]; // prints "orange"
unset($fruits["holes"][0]);  // remove "first"

// Crear una nueva array multi-dimensional
$juices["apple"]["green"] = "good";
?>

La asignación de arrays siempre involucra la copia de valores. Use el operador de referencia para copiar un array por referencia.

<?php
$arr1 
= array(23);
$arr2 $arr1;
$arr2[] = 4// $arr2 ha cambiado,
             // $arr1 sigue siendo array(2, 3)
            
$arr3 = &$arr1;
$arr3[] = 4// ahora $arr1 y $arr3 son iguales
?>
add a note add a note

User Contributed Notes 20 notes

up
123
mlvljr
12 years ago
please note that when arrays are copied, the "reference status" of their members is preserved (http://www.php.net/manual/en/language.references.whatdo.php).
up
54
thomas tulinsky
8 years ago
I think your first, main example is needlessly confusing, very confusing to newbies:

$array = array(
    "foo" => "bar",
    "bar" => "foo",
);

It should be removed.

For newbies:
An array index can be any string value, even a value that is also a value in the array.
The value of array["foo"] is "bar".
The value of array["bar"] is "foo"

The following expressions are both true:
$array["foo"] == "bar"
$array["bar"] == "foo"
up
34
liberchen at gmail dot com
6 years ago
Since PHP 7.1, the string will not be converted to array automatically.

Below codes will fail:

$a=array();
$a['a']='';
$a['a']['b']=''; 
//Warning: Illegal string offset 'b'
//Warning: Cannot assign an empty string to a string offset

You have to change to as below:

$a=array();

$a['a']=array(); // Declare it is an array first
$a['a']['b']='';
up
29
Yesterday php&#39;er
7 years ago
--- quote ---
Note:
Both square brackets and curly braces can be used interchangeably for accessing array elements
--- quote end ---

At least for php 5.4 and 5.6; if function returns an array, the curly brackets does not work directly accessing function result, eg. WillReturnArray(){1} . This will give "syntax error, unexpected '{' in...".
Personally I use only square brackets, expect for accessing single char in string. Old habits...
up
59
jeff splat codedread splot com
19 years ago
Beware that if you're using strings as indices in the $_POST array, that periods are transformed into underscores:

<html>
<body>
<?php
    printf
("POST: "); print_r($_POST); printf("<br/>");
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    <input type="hidden" name="Windows3.1" value="Sux">
    <input type="submit" value="Click" />
</form>
</body>
</html>

Once you click on the button, the page displays the following:

POST: Array ( [Windows3_1] => Sux )
up
56
ken underscore yap atsign email dot com
16 years ago
"If you convert a NULL value to an array, you get an empty array."

This turns out to be a useful property. Say you have a search function that returns an array of values on success or NULL if nothing found.

<?php $values = search(...); ?>

Now you want to merge the array with another array. What do we do if $values is NULL? No problem:

<?php $combined = array_merge((array)$values, $other); ?>

Voila.
up
45
chris at ocportal dot com
10 years ago
Note that array value buckets are reference-safe, even through serialization.

<?php
$x
='initial';
$test=array('A'=>&$x,'B'=>&$x);
$test=unserialize(serialize($test));
$test['A']='changed';
echo
$test['B']; // Outputs "changed"
?>

This can be useful in some cases, for example saving RAM within complex structures.
up
42
ia [AT] zoznam [DOT] sk
18 years ago
Regarding the previous comment, beware of the fact that reference to the last value of the array remains stored in $value after the foreach:

<?php
foreach ( $arr as $key => &$value )
{
   
$value = 1;
}

// without next line you can get bad results...
//unset( $value );

$value = 159;
?>

Now the last element of $arr has the value of '159'. If we remove the comment in the unset() line, everything works as expected ($arr has all values of '1').

Bad results can also appear in nested foreach loops (the same reason as above).

So either unset $value after each foreach or better use the longer form:

<?php
foreach ( $arr as $key => $value )
{
   
$arr[ $key ] = 1;
}
?>
up
11
anisgazig at gmail dot com
5 years ago
//array keys are always integer and string data type and array values are all data type
//type casting and overwriting(data type of array key)
//----------------------------------------------------
$arr = array(
1=>"a",//int(1)
"3"=>"b",//int(3)
"08"=>"c",//string(2)"08"
"80"=>"d",//int(80)
"0"=>"e",//int(0)
"Hellow"=>"f",//string(6)"Hellow"
"10Hellow"=>"h",//string(8)"10Hellow"
1.5=>"j",//int(1.5)
"1.5"=>"k",//string(3)"1.5"
0.0=>"l",//int(0)
false=>"m",//int(false)
true=>"n",//int(true)
"true"=>"o",//string(4)"true"
"false"=>"p",//string(5)"false"
null=>"q",//string(0)""
NULL=>"r",//string(0)"" note null and NULL are same
"NULL"=>"s",//string(4)"NULL" ,,,In last element of multiline array,comma is better to used.
);
//check the data type name of key
foreach ($arr as $key => $value) {
var_dump($key);
echo "<br>";
}

//NOte :array and object data type in keys are Illegal ofset.......
up
2
ivail89 at mail dot ru
3 years ago
Function unset can delete array's element by reference only when you specify source array. See example:
<?php
$array
= [1, 2, 3, 4, 5];
foreach (
$array as $k => &$v){
    if (
$k >= 3){
        unset(
$v);
    }
}
echo
count($array); // 5
?>
In this case unset delete only reference, however original array didn't change.

Or different example:
<?php
$arr
= [1, 2];
$a = &$arr[0];
unset(
$a);
count($arr); // 2
?>

So for deleting element from first example need use key and array.
<?php
// ...
 
unset($array[$k]);
// ...
?>
up
31
lars-phpcomments at ukmix dot net
19 years ago
Used to creating arrays like this in Perl?

@array = ("All", "A".."Z");

Looks like we need the range() function in PHP:

<?php
$array
= array_merge(array('All'), range('A', 'Z'));
?>

You don't need to array_merge if it's just one range:

<?php
$array
= range('A', 'Z');
?>
up
3
dylanfj700 at gmail dot com
4 years ago
// Before php 5.4
$array = array(1,2,3);

// since php 5.4 , short syntax
$array = [1,2,3];

// I recommend using the short syntax if you have php version >= 5.4
up
7
tissus
6 years ago
In array(key=>value) construct key is also an expression.
This works fine:
  $a = array(
    1     =>0,
    1+1   =>1,
    $k    =>2,
    $x.'4'=>3
  );
up
22
caifara aaaat im dooaat be
18 years ago
[Editor's note: You can achieve what you're looking for by referencing $single, rather than copying it by value in your foreach statement. See http://php.net/foreach for more details.]

Don't know if this is known or not, but it did eat some of my time and maybe it won't eat your time now...

I tried to add something to a multidimensional array, but that didn't work at first, look at the code below to see what I mean:

<?php

$a1
= array( "a" => 0, "b" => 1 );
$a2 = array( "aa" => 00, "bb" => 11 );

$together = array( $a1, $a2 );

foreach(
$together as $single ) {
   
$single[ "c" ] = 3 ;
}

print_r( $together );
/* nothing changed result is:
Array
(
    [0] => Array
        (
            [a] => 0
            [b] => 1
        )
    [1] => Array
        (
            [aa] => 0
            [bb] => 11
        )
) */

foreach( $together as $key => $value ) {
   
$together[$key]["c"] = 3 ;
}

print_r( $together );

/* now it works, this prints
Array
(
    [0] => Array
        (
            [a] => 0
            [b] => 1
            [c] => 3
        )
    [1] => Array
        (
            [aa] => 0
            [bb] => 11
            [c] => 3
        )
)
*/

?>
up
7
note dot php dot lorriman at spamgourmet dot org
10 years ago
There is another kind of array (php>=  5.3.0) produced by

$array = new SplFixedArray(5);

Standard arrays, as documented here, are marvellously flexible and, due to the underlying hashtable, extremely fast for certain kinds of lookup operation.

Supposing a large string-keyed array

$arr=['string1'=>$data1, 'string2'=>$data2 etc....]

when getting the keyed data with

$data=$arr['string1'];

php does *not* have to search through the array comparing each key string to the given key ('string1') one by one, which could take a long time with a large array. Instead the hashtable means that php takes the given key string and computes from it the memory location of the keyed data, and then instantly retrieves the data. Marvellous! And so quick. And no need to know anything about hashtables as it's all hidden away.

However, there is a lot of overhead in that. It uses lots of memory, as hashtables tend to (also nearly doubling on a 64bit server), and should be significantly slower for integer keyed arrays than old-fashioned (non-hashtable) integer-keyed arrays. For that see more on SplFixedArray :

http://uk3.php.net/SplFixedArray

Unlike a standard php (hashtabled) array, if you lookup by integer then the integer itself denotes the memory location of the data, no hashtable computation on the integer key needed. This is much quicker. It's also quicker to build the array compared to the complex operations needed for hashtables. And it uses a lot less memory as there is no hashtable data structure. This is really an optimisation decision, but in some cases of large integer keyed arrays it may significantly reduce server memory and increase performance (including the avoiding of expensive memory deallocation of hashtable arrays at the exiting of the script).
up
-2
Denise Ignatova
6 years ago
When creating arrays , if we have an element with the same value as another element from the same array, we would expect PHP instead of creating new zval container to increase the refcount and point the duplicate symbol to the same zval. This is true except for value type integer.
Example:

$arr = ['bebe' => 'Bob', 'age' => 23, 'too' => 23 ];
xdebug_debug_zval( 'arr' );

Output:
arr:

(refcount=2, is_ref=0)
array (size=3)
  'bebe' => (refcount=1, is_ref=0)string 'Bob' (length=3)
  'age' => (refcount=0, is_ref=0)int 23
  'too' => (refcount=0, is_ref=0)int 23

but :
$arr = ['bebe' => 'Bob', 'age' => 23, 'too' => '23' ];
xdebug_debug_zval( 'arr' );

will produce:
arr:

(refcount=2, is_ref=0)
array (size=3)
  'bebe' => (refcount=1, is_ref=0)string 'Bob' (length=3)
  'age' => (refcount=0, is_ref=0)int 23
  'too' => (refcount=1, is_ref=0)string '23' (length=2)
or :

$arr = ['bebe' => 'Bob', 'age' => [1,2], 'too' => [1,2] ];
xdebug_debug_zval( 'arr' );

Output:
arr:

(refcount=2, is_ref=0)
array (size=3)
  'bebe' => (refcount=1, is_ref=0)string 'Bob' (length=3)
  'age' => (refcount=2, is_ref=0)
    array (size=2)
      0 => (refcount=0, is_ref=0)int 1
      1 => (refcount=0, is_ref=0)int 2
  'too' => (refcount=2, is_ref=0)
    array (size=2)
      0 => (refcount=0, is_ref=0)int 1
      1 => (refcount=0, is_ref=0)int 2
up
-2
Anonymous
4 years ago
Wrappers for (array), returns array with normalize keys (without prefix):
<?php
function to_array_recursive($value): array
{
        if (!
is_object($value)) {
                return (array)
$value;
        }
       
$class = get_class($value);
       
$arr = [];
       
foreact ((array)  $value as $key => $val) {
               
$key = str_replace(["\0*\0", "\0{$class}\0"], '', $key);
               
$arr[$key] = is_object($val) ? to_array_recursive($val) : $val;
        }
        return
$arr;
}

function
to_array($value): array
{
       
$arr = (array) $value;
        if (!
is_object($value)) {
                return
$arr;
        }
       
$class = get_class($value);
       
$keys = str_replace(["\0*\0", "\0{$class}\0"], '', array_keys($arr));
        return
array_combine($keys, $arr);
}
?>
Demo:
<?php
class Test
{
        protected
$var = 1;
        protected
$var2;
        private
$TestVar = 3;
       
    public function
__construct($isParent = true)
    {
        if (
$isParent) {
           
$this->var2 = new self(! $isParent);
        }
    }
}

$obj = new Test();
var_dump((array) $obj, to_array_recursive($obj));
?>
up
-9
ivegner at yandex dot ru
10 years ago
Note that objects of classes extending ArrayObject SPL class are treated as arrays, and not as objects when converting to array.

<?php
class ArrayObjectExtended extends ArrayObject
{
    private
$private = 'private';
    public
$hello = 'world';
}

$object = new ArrayObjectExtended();
$array = (array) $object;

// This will not expose $private and $hello properties of $object,
// but return an empty array instead.
var_export($array);
?>
up
-14
Walter Tross
13 years ago
It is true that "array assignment always involves value copying", but the copy is a "lazy copy". This means that the data of the two variables occupy the same memory as long as no array element changes.

E.g., if you have to pass an array to a function that only needs to read it, there is no advantage at all in passing it by reference.
up
-27
gfr7oo at gmail dot com
4 years ago
<?php
function getArray() {
    return array(
1, 2, 3);
}

// on PHP 5.4
$secondElement = getArray()[1];

// previously
$tmp = getArray();
$secondElement = $tmp[1];

// or
list(, $secondElement) = getArray();
?>

Here list(, $secondElement) = getArray();
and list($secondElement) = getArray(); is the same thing
so you can avoid the "comma" to avoid the confusion.
To Top