Sei sulla pagina 1di 26

Arrays

Un array en PHP es en realidad un mapa ordenado. Un mapa es un tipo de datos que


asocia valorescon claves. Este tipo se optimiza para varios usos diferentes; se puede
emplear como un array, lista (vector), tabla asociativa (tabla hash - una implementacin
de un mapa), diccionario, coleccin, pila, cola, y posiblemente ms. Ya que los valores
de un array pueden ser otros arrays, tambin son posibles rboles y arrays
multidimensionales.
Una explicacin 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 ms
informacin, consulte la extensa literatura que existe sobre este amplio tema.

Sintaxis
Especificacin con array()
Un array puede ser creado con el constructor del lenguaje array(). ste toma cualquier
nmero de parejas clave => valor como argumentos.
array(
clave => valor,
clave2 => valor2,
clave3 => valor3,
...
)

La coma despus del ltimo elemento del array es opcional, pudindose omitir. Esto
normalmente se hace para arrays de una nica lnea, es decir, es preferible array(1,
2) que array(1, 2, ). Por otra parte, para arrays multilnea, la coma final se usa
frecuentemente, ya que permite una adicin ms sencilla de nuevos elementos al final.
A partir de PHP 5.4 tambin 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.

Adems, se darn los siguientes amoldamientos de clave:


o Un strings que contenga un integer vlido ser amoldado al tipo integer. P.ej. la
clave "8" en realidad ser almacenada como 8. Por otro lado "08" no ser
convertido, ya que no es un nmero integer decimal vlido.
o Un floats tambin 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.
o Un booleano son amoldados a integers tambin, es decir, la clave true en
realidad ser almacenada como 1 y la clave false como 0.
o Un null ser amoldado a un string vaco, es decir, la clave null en realidad ser
almacenada como"".
o 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 declaracin del array usan la misma clave, slo se utilizar la
ltima, siendo los dems son 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 sera:


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

Como todas las claves en el ejemplo anterior se convierten en 1, los valores sern
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 sera:


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 sera:


array(4) {
[0]=>
string(3)
[1]=>
string(3)
[2]=>
string(5)
[3]=>
string(5)
}

"foo"
"bar"
"hello"
"world"

Es posible especificar la clave slo para algunos elementos y excluir a los dems:
Ejemplo #5 Claves no en todos los elementos
<?php
$array = array(
"a",
"b",
6 => "c",
"d",
);
var_dump($array);
?>

El resultado del ejemplo sera:

array(4) {
[0]=>
string(1)
[1]=>
string(1)
[6]=>
string(1)
[7]=>
string(1)
}

"a"
"b"
"c"
"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 sera:


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} tendrn 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 funcin o mtodo directamente. Antes slo 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(1, 2, 3);
}
// 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.
Creacin/modificacin con la sintaxis de corchete
Un array existente puede ser modificado estableciendo explcitamente valores en l.
Esto se realiza asignando valores al array, especificando la clave entre corchetes. Esta
tambin se puede omitir, resultando en un par de corchetes vacos ([]).
$arr[clave] = valor;
$arr[] = valor;
// clave puede ser un integer o un string
// valor puede ser cualquier valor de cualquier tipo

Si $arr an no existe, se crear, siendo tambin esta forma una alternativa de crear
un array. Sin embargo, se desaconsejada esta prctica porque que si $arr ya contiene
algn valor (p.ej. un stringde una variable de peticin), este estar en su lugar y [] puede
significar realmente el operador de acceso a cadenas. Siempre es mejor inicializar
variables mediante una asignacin directa.
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
funcin unset() con ste.
<?php
$arr = array(5 => 1, 12 => 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);
?>

Nota:

// Esto elimina el array completo

Como se mencion anteriormente, si no se especifica una clave, se toma el mximo de


los ndicesinteger existentes, y la nueva clave ser ese valor mximo ms 1 (aunque al
menos 0). Si todava no existen ndices integer, la clave ser 0 (cero).
Tenga en cuenta que la clave integer mxima utilizada para ste no es necesario que
actualmente exista en el array. sta slo debe haber existido en el array en algn
momento desde la ltima vez que el array fu re-indexado. El siguiente ejemplo ilustra
este comportamiento:
<?php
// Crear un array simple.
$array = array(1, 2, 3, 4, 5);
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 sera:


Array
(
[0]
[1]
[2]
[3]
[4]
)
Array
(
)
Array
(
[5]
)
Array
(
[0]
[1]
)

=>
=>
=>
=>
=>

1
2
3
4
5

=> 6

=> 6
=> 7

Funciones tiles
Hay un buen nmero de funciones tiles para trabajar con arrays. Vase la
seccin funciones de array.
Nota:

La funcin 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 funcin array_values().
<?php
$a = array(1 =>
unset($a[2]);
/* producir un
$a = array(1
y NO
$a = array(1
*/

'uno', 2 => 'dos', 3 => 'tres');


array que se ha definido como
=> 'uno', 3 => 'tres');
=> 'uno', 2 =>'tres');

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

La estructura de control foreach existe especficamente para arrays. sta provee una
manera fcil 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
comn encontrar este tipo de sintaxis en scripts viejos:
<?php
$foo[bar] = 'enemy';
echo $foo[bar];
// etc
?>

Esto est mal, pero funciona. La razn es que este cdigo tiene una constante indefinida
(bar) en lugar de un string ('bar' - observe las comillas). Puede que en el futuro PHP
defina constantes que, desafortunadamente para tales tipo de cdigo, tengan el mismo
nombre. Funciona porque PHP automticamente convierte un string puro (un string sin
comillas que no corresponde con ningn smbolo 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.
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(1, 2);
$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 sera:


Revisando 0:
Notice: Undefined index:
Mal:
Bien: 1
Notice: Undefined index:
Mal:
Bien: 1
Revisando 1:
Notice: Undefined index:
Mal:
Bien: 2
Notice: Undefined index:
Mal:
Bien: 2

$i in /path/to/script.html on line 9
$i in /path/to/script.html on line 11

$i in /path/to/script.html on line 9
$i in /path/to/script.html on line 11

Ms 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 tambin 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 'veg
gie'
// 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 caden
a. 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 excepcin, 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 intrprete como:


// Parse error: parse error, expecting T_STRING' or T_VARIABLE' or T_N
UM_STRING'
// Esto por supuesto se aplica tambin al uso de superglobales en cade
nas
print "Hello $arr['fruit']";
print "Hello $_GET['foo']";
// La concatenacin es otra opcin
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 sern inmediatamente visibles. Por
omisin,error_reporting se encuentra configurado para no mostrarlos.
Tal y como se indica en la seccin de sintaxis, lo que existe entre los corchetes
cuadrados ('[' y ']') debe ser una expresin. Esto quiere decir que cdigo como el
siguiente funciona:
<?php
echo $arr[somefunc($bar)];
?>

Este es un ejemplo del uso de un valor devuelto por una funcin como ndice del array.
PHP tambin 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 tambin un identificador vlido, 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 algn momento en el futuro, puede que el equipo de PHP quiera usar otra constante
o palabra clave, o una constante proveniente de otro cdigo 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 vlido no rodear
los ndices de array con comillas, as que "$foo[bar]" es vlido. Consulte los ejemplos

anteriores para ms detalles sobre el porqu, as como la seccin sobre procesamiento


de variables en cadenas.

Conversin a array
Para cualquiera de los tipos: integer, float, string, boolean y resource, convertir un valor
a un arrayresulta 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 delobject. 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 A {
private $A; //
}

Este campo se convertir en '\0A\0A'

class B extends A {
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 vaco.

Comparacin
Es posible comparar arrays con la funcin array_diff() y mediante operadores de arrays.

Ejemplos
El tipo array en PHP es bastante verstil. Aqu hay algunos ejempos:
<?php
// Esto:
$a = array( 'color'
'taste'
'shape'
'name'
4
);

=> 'red',
=> 'sweet',
=> 'round',
=> 'apple',
// 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 =
$b[]
$b[]
$b[]

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

// Despus de que se ejecute el cdigo, $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 numricas
$array = array( 7,
8,
0,
156,
-10
);
// esto es lo mismo que array(0 => 7, 1 => 8, ...)
$switching = array(

a 5)

5
3
'a'

=>
=>
=>

10, // key = 0
6,
7,
4,
11, // key = 6 (el ndice entero mximo er

'8' => 2, // key = 8 (integer!)


'02' => 77, // key = '02'
0
=> 12 // el valor 10 ser reemplazado por 12

);
// array vaco
$empty = array();
?>

Ejemplo #9 Coleccin
<?php
$colors = array('rojo', 'azul', 'verde', 'amarillo');

foreach ($colors as $color) {


echo "Le gusta el $color?\n";
}
?>

El resultado del ejemplo sera:


Le
Le
Le
Le

gusta
gusta
gusta
gusta

el
el
el
el

rojo?
azul?
verde?
amarillo?

Modificar los valores del array directamente es posible a partir de PHP 5, pasndolos
por referencia. Las versiones anteriores necesitan una solucin alternativa:
Ejemplo #10 Cambiando elemento en el bucle
<?php
// PHP 5
foreach ($colors as &$color) {
$color = strtoupper($color);
}
unset($color); /* se asegura de que escrituras subsiguientes a $color
no modifiquen el ltimo elemento del arrays */
// Alternativa para versiones anteriores
foreach ($colors as $key => $color) {
$colors[$key] = strtoupper($color);
}
print_r($colors);
?>

El resultado del ejemplo sera:


Array
(
[0]
[1]
[2]
[3]
)

=>
=>
=>
=>

ROJO
AZUL
VERDE
AMARILLO

Este ejemplo crea un array con base uno.


Ejemplo #11 ndice con base 1
<?php
$firstquarter = array(1 => 'Enero', 'Febrero', 'Marzo');
print_r($firstquarter);
?>

El resultado del ejemplo sera:


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 seccin sobre funciones de arrays para ms informacin. La
funcin count() puede ser usada para contar el nmero 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, tambin 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",
5 => "second",
"third"
)

);

// Algunos ejemplos que hacen referencia a los valores del array anter
ior
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 asignacin de arrays siempre involucra la copia de valores. Use el operador de


referencia para copiar un array por referencia.
<?php
$arr1 = array(2, 3);
$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

User Contributed Notes 20 notes


up
down
38
perske at uni-muenster dot de
1 year ago

Regarding this note: Strings containing valid integers will be cast


to the integer type.
This is true only for decimal integers without leading +, but not
for octal, hexadecimal, or binary integers.
Example:
<?php
$array = array(
"0"
=> "a",
"-1" => "b",
"+1" => "c",
"00" => "d",
"01" => "e",
"0x1" => "f",
);
var_dump($array);
?>
This example will output:
array(7) {
[0]=>
string(1)
[-1]=>
string(1)
["+1"]=>
string(1)
["00"]=>
string(1)

"a"
"b"
"c"
"d"

["01"]=>
string(1) "e"
["0x1"]=>
string(1) "f"

Thus different strings are always mapped to different array keys.

up
down
79
mlvljr
5 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
down
21
thomas tulinsky
6 months 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
down
21
mathiasgrimm at gmail dot com
<?php

1 year ago

$a['a'] = null;
$a['b'] = array();
echo $a['a']['non-existent']; // DOES NOT throw an E_NOTICE error as
expected.
echo $a['b']['non-existent']; // throws an E_NOTICE as expected

?>
I added this bug to bugs.php.net (https://bugs.php.net/bug.php?
id=68110)
however I made tests with php4, 5.4 and 5.5 versions and all behave
the same way.
This, in my point of view, should be cast to an array type and throw
the same error.
This is, according to the documentation on this page, wrong.
From doc:
"Note:
Attempting to access an array key which has not been defined is the
same as accessing any other undefined variable: an E_NOTICE-level
error message will be issued, and the result will be NULL."

up
down
48
ken underscore yap atsign email dot com
8 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
down
41
jeff splat codedread splot com
11 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
down
23
ivegner at yandex dot ru
3 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
down
13
note dot php dot lorriman at spamgourmet dot org
2 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 oldfashioned (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
down
38
lars-phpcomments at ukmix dot net
Used to creating arrays like this in Perl?

11 years ago

@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
down
24
chris at ocportal dot com
3 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
down
33
ia [AT] zoznam [DOT] sk
10 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
down
19
caifara aaaat im dooaat be
11 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/foreachfor 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
down
7
Walter Tross
6 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
down
-1
martijntje at martijnotto dot nl
4 years ago

Please note that adding the magic __toString() method to your objects
will not allow you to seek an array with it, it still throws an
Illegal Offset warning.
The solution is to cast it to a string first, like this
$array[(string) $stringableObject]

up
down
-5
brta dot akos at gmail dot com
2 years ago
Why not to user one-based arrays:
<?php
$a = array(1 => 'a', 'b', 'd');
print_r($a);
array_splice($a,2,0,'c');
print_r($a);
?>
output:
Array ( [1] => a [2] => b [3] => d ) Array ( [0] => a [1] => b [2] =>
c [3] => d )

up
down
-11
Anonymous
9 years ago

This page should include details about how associative arrays are
implemened inside PHP; e.g. using hash-maps or b-trees.

This has important implictions on the permance characteristics of


associative arrays and how they should be used; e.g. b-tree are slow
to insert but handle collisions better than hashmaps. Hashmaps are

faster if there are no collisions, but are slower to retrieve when


there are collisions. These factors have implictions on how
associative arrays should be used.

up
down
-5
php at markuszeller dot com
3 months ago
Sometimes I need to match fieldnames from database tables. But if a
source field is used many times you can not use a hash "=>", because
it overrides the key.
My approach is to use a comma separated array and use a while-loop in
conjunction with each. Having that you can iterate key/value based,
but may have a key multiple times.
$fieldmap = array
(
'id', 'import_id',
'productname', 'title',
'datetime_online', 'onlineDate',
'datetime_test_final', 'offlineDate',
'active', 'status',
'questionaire_intro', 'text_lead',
'datetime_online', 'createdAt',
'datetime_online', 'updatedAt'
);
while(list(,$key) = each($fieldmap))
{
list(,$value) = each($fieldmap);
echo "$key: $value\n";
}

up
down
-15
Spudley
9 years ago
On array recursion...
Given the following code:
<?php
$myarray = array('test',123);
$myarray[] = &$myarray;
print_r($myarray);
?>
The print_r() will display *RECURSION* when it gets to the third
element of the array.
There doesn't appear to be any other way to scan an array for
recursive references, so if you need to check for them, you'll have to
use print_r() with its second parameter to capture the output and look

for the word *RECURSION*.


It's not an elegant solution, but it's the only one I've found, so I
hope it helps someone.

up
down
-14
aditycse at gmail dot com
1 year ago
/*
* Name : Aditya Mehrotra
* Email: aditycse@gmail.com
*/
<?php
//Array can have following data type in key i.e string,integer
//Behaviour of array in case of array key has data type float or
double
$exampleArray = array(0,
1,
"2.99999999" => 56,
2 => 2,
3.9999 => 3,
3 => 3.1,
true => 4,
false => 6,
);
//array structure
print_r($exampleArray);
/* Array
(
[0] => 6
[1] => 4
[2.99999999] => 56
[2] => 2
[3] => 3.1
)
*/
//array of array keys
print_r(array_keys($exampleArray));
/*
Array
(
[0] => 0
[1] => 1
[2] => 2.99999999
[3] => 2
[4] => 3
)
*/

up
down
-75

carl at linkleaf dot com


9 years ago

Its worth noting that there does not appear to be any functional
limitations on the length or content of string indexes. The string
indexes for your arrays can contain any characters, including new line
characters, and can be of any length:
<?php
$key = "XXXXX";
$test = array($key => "test5");
for ($x = 0; $x < 500; $x++) {
$key .= "X";
$value = "test" . strlen($key);
$test[$key] = $value;
}
echo "<pre>";
print_r($test);
echo "</pre>";
?>
Keep in mind that using extremely long array indexes is not a good
practice and could cost you lots of extra CPU time. However, if you
have to use a long string as an array index you won't have to worry
about the length or content.

Una caracterstica muy potente de los Arrays es que cada uno de sus
elementos puede ser, a su vez, otro Array (consiguiendo Arrays,
de Arrays, de Arrays, de...) en lo que se
conoce como Arrays multimensionales. Esto permite representar
estructuras ms complejas de datos, al estilo de tablas o bases de
datos.

Este artculo simplemente supone una ampliacin del publicado


anteriormente sobre Arrays bidimensionales en PHP. Os dejamos a
continuacin un video publicado en Youtube por el maestro Jess
Conde donde nos regala un ejemplo de un Array tridimensional y
distintas formas de recorrerlo para poder mostrar los elementos que
contiene en pantalla.

En este tutorial tambin conoceremos el uso de la funcin sort, que


nos permiteordenar los elementos de un Array por orden
alfabtico (recuerda que las maysculas siempre tienen prioridad
sobre las minsculas, as que una Zmayscula se posicionar por
delante que una a minscula).
<?php
$series= array("Peaky Blinders", "Carnivale",
"mad Men", "Game of Thrones");
sort($series);
echo $series[0]; // Mostrar Carnivale
echo $series[3]; // Mostrar mad Men
?>
Imaginemos que tenemos ahora un Array asociativo que almacena el
nmero de temporadas que contiene cada serie.

<?php
$series= array("Peaky Blinders"=>2,
"Carnivale"=>4, "mad Men"=>6, "Game of Thrones"=>3);
asort($series);
echo $series[0]; // Mostrar Carnivale
echo $series[3]; // Mostrar mad Men
?>
En este ejemplo la funcin asort nos permite ordenar los elementos de
un Arrayasociativo por los valores de los elementos en orden
ascendente. Si quisisemos ordenar los elementos por la clave en vez
de por el valor podemos utilizar la funcin ksort.
Estas tres funciones que nos permiten clasificar los elementos de
un Array en orden ascendente tienen su funcin inversa, que
consiguen el mismo resultado pero clasificando los elementos en
orden descendente. Para conseguirlo, es tan sencillo como aadir
una r (de reverse) antes de cada una de las tres funciones.
<?php
$series= array("Peaky Blinders"=>2,
"Carnivale"=>4, "mad Men"=>6, "Game of Thrones"=>3);
rasort($series);
echo $series[0]; // Mostrar mad Men
echo $series[3]; // Mostrar Peaky Blinders
?>
http://www.ciclodeinformatica.es/2014/11/arrays-multidimensionales.html

Potrebbero piacerti anche