Sie sind auf Seite 1von 22

PHP: Arrays - Manual

http://php.net/manual/es/language.types.array.php

Downloads
Documentation
Get Involved
Help

Search
PHPKonf: Istanbul PHP Conference 2017
Getting Started
Introduction
A simple tutorial
Language Reference
Basic syntax
Types
Variables
Constants
Expressions
Operators
Control Structures
Functions
Classes and Objects
Namespaces
Errors
Exceptions
Generators
References Explained
Predefined Variables
Predefined Exceptions
Predefined Interfaces and Classes
Context options and parameters
Supported Protocols and Wrappers
Security
Introduction
General considerations
Installed as CGI binary
Installed as an Apache module
Session Security
Filesystem Security
Database Security
Error Reporting
Using Register Globals
User Submitted Data
Magic Quotes
Hiding PHP
Keeping Current
Features
HTTP authentication with PHP
Cookies
Sessions
Dealing with XForms
Handling file uploads
Using remote files
Connection handling
Persistent Database Connections
Safe Mode
Command line usage
Garbage Collection

1 de 22

14/01/17 11:16

PHP: Arrays - Manual

http://php.net/manual/es/language.types.array.php

DTrace Dynamic Tracing


Function Reference
Affecting PHP's Behaviour
Audio Formats Manipulation
Authentication Services
Command Line Specific Extensions
Compression and Archive Extensions
Credit Card Processing
Cryptography Extensions
Database Extensions
Date and Time Related Extensions
File System Related Extensions
Human Language and Character Encoding Support
Image Processing and Generation
Mail Related Extensions
Mathematical Extensions
Non-Text MIME Output
Process Control Extensions
Other Basic Extensions
Other Services
Search Engine Extensions
Server Specific Extensions
Session Extensions
Text Processing
Variable and Type Related Extensions
Web Services
Windows Only Extensions
XML Manipulation
GUI Extensions
Keyboard Shortcuts
?
This help
j
Next menu item
k
Previous menu item
gp
Previous man page
gn
Next man page
G
Scroll to bottom
gg
Scroll to top
gh
Goto homepage
gs
Goto search
(current page)
/
Focus search box
Objetos
Cadenas de caracteres (Strings)
Manual de PHP
Referencia del lenguaje
Tipos

2 de 22

14/01/17 11:16

PHP: Arrays - Manual

Change language:

http://php.net/manual/es/language.types.array.php

Spanish

Edit Report a Bug

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 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",
);
//apartirdePHP5.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:
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.
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.

3 de 22

14/01/17 11:16

PHP: Arrays - Manual

http://php.net/manual/es/language.types.array.php

Un booleano son amoldados a integers tambin, es decir, la clave true en realidad ser
almacenada como 1 y la clave false como 0.
Un null ser amoldado a un string vaco, 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 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");

4 de 22

14/01/17 11:16

PHP: Arrays - Manual

http://php.net/manual/es/language.types.array.php

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"]);
?>

5 de 22

14/01/17 11:16

PHP: Arrays - Manual

http://php.net/manual/es/language.types.array.php

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
functiongetArray(){
returnarray(1,2,3);
}
//enPHP5.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 string de 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);

6 de 22

14/01/17 11:16

PHP: Arrays - Manual

http://php.net/manual/es/language.types.array.php

$arr[]=56;//Estoeslomismoque$arr[13]=56;
//enestepuntodeelscript
$arr["x"]=42;//Estoagregaunnuevoelementoa
//elarrayconlaclave"x"

unset($arr[5]);//Estoeliminaelelementodelarray
unset($arr);//Estoeliminaelarraycompleto
?>

Nota:
Como se mencion anteriormente, si no se especifica una clave, se toma el mximo de
los ndices integer 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
//Crearunarraysimple.
$array=array(1,2,3,4,5);
print_r($array);
//Ahoraeliminacadaelemento,perodejaelmismoarrayintacto:
foreach($arrayas$i=>$value){
unset($array[$i]);
}
print_r($array);
//Agregarunelemento(notequelanuevaclavees5,enlugarde0).
$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

7 de 22

14/01/17 11:16

PHP: Arrays - Manual

http://php.net/manual/es/language.types.array.php

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=>'uno',2=>'dos',3=>'tres');
unset($a[2]);
/*producirunarrayquesehadefinidocomo
$a=array(1=>'uno',3=>'tres');
yNO
$a=array(1=>'uno',2=>'tres');
*/
$b=array_values($a);
//Ahora$besarray(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);
//Arraysimple:
$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";

8 de 22

14/01/17 11:16

PHP: Arrays - Manual

http://php.net/manual/es/language.types.array.php

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
//Mostrartodosloserrores
error_reporting(E_ALL);
$arr=array('fruit'=>'apple','veggie'=>'carrot');
//Correcto
print$arr['fruit'];//apple
print$arr['veggie'];//carrot
//Incorrecto.EstofuncionaperotambingeneraunerrordePHPde
//nivelE_NOTICEyaquenohaydefinidaunaconstantellamadafruit
//
//Notice:Useofundefinedconstantfruit-assumed'fruit'in...
print$arr[fruit];//apple
//Estodefineunaconstanteparademostrarloquepasa.Elvalor'veggie'
//esasignadoaunaconstantellamadafruit.
define('fruit','veggie');
//Noteladiferenciaahora
print$arr['fruit'];//apple
print$arr[fruit];//carrot
//Losiguienteestbienyaqueseencuentraalinteriordeunacadena.Lasconstantesnosonprocesadasal
//interiordecadenas,asquenoseproduceunerrorE_NOTICEaqu
print"Hello$arr[fruit]";//Helloapple
//Conunaexcepcin,loscorchetesquerodeanlasmatricesal
//interiordecadenaspermitenelusodeconstantes
print"Hello{$arr[fruit]}";//Hellocarrot
print"Hello{$arr['fruit']}";//Helloapple
//Estonofunciona,resultaenunerrordeintrpretecomo:
//Parseerror:parseerror,expectingT_STRING'orT_VARIABLE'orT_NUM_STRING'
//Estoporsupuestoseaplicatambinalusodesuperglobalesencadenas
print"Hello$arr['fruit']";
print"Hello$_GET['foo']";
//Laconcatenacinesotraopcin
print"Hello".$arr['fruit'];//Helloapple
?>

9 de 22

14/01/17 11:16

PHP: Arrays - Manual

http://php.net/manual/es/language.types.array.php

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]="Unerrorfatalhaocurrido";
$error_descriptions[E_WARNING]="PHPprodujounaadvertencia";
$error_descriptions[E_NOTICE]="Estaesunanoticiainformal";
?>

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]="Unerrorfatalhaocurrido";
$error_descriptions[2]="PHPprodujounaadvertencia";
$error_descriptions[8]="Estaesunanoticiainformal";
?>

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
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
classA{
private$A;//Estecamposeconvertiren'\0A\0A'
}

10 de 22

14/01/17 11:16

PHP: Arrays - Manual

http://php.net/manual/es/language.types.array.php

classBextendsA{
private$A;//Estecamposeconvertiren'\0B\0A'
public$AA;//Estecamposeconvertiren'AA'
}
var_dump((array)newB());
?>

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'=>'red',
'taste'=>'sweet',
'shape'=>'round',
'name'=>'apple',
4//laclaveser0
);
$b=array('a','b','c');
//...escompletamenteequivalentea
$a=array();
$a['color']='red';
$a['taste']='sweet';
$a['shape']='round';
$a['name']='apple';
$a[]=4;//laclaveser0
$b=array();
$b[]='a';
$b[]='b';
$b[]='c';
//Despusdequeseejecuteelcdigo,$aserelarray
//array('color'=>'red','taste'=>'sweet','shape'=>'round',
//'name'=>'apple',0=>4),y$bserelarray
//array(0=>'a',1=>'b',2=>'c'),osimplementearray('a','b','c').
?>

Ejemplo #8 Uso de array()


<?php
//Arraycomomapadepropiedades
$map=array('version'=>4,
'OS'=>'Linux',
'lang'=>'english',
'short_tags'=>true
);

//Keysestrictamentenumricas

11 de 22

14/01/17 11:16

PHP: Arrays - Manual

http://php.net/manual/es/language.types.array.php

$array=array(7,
8,
0,
156,
-10
);
//estoeslomismoquearray(0=>7,1=>8,...)
$switching=array(10,//key=0
5=>6,
3=>7,
'a'=>4,
11,//key=6(elndiceenteromximoera5)
'8'=>2,//key=8(integer!)
'02'=>77,//key='02'
0=>12//elvalor10serreemplazadopor12
);

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

Ejemplo #9 Coleccin
<?php
$colors=array('rojo','azul','verde','amarillo');
foreach($colorsas$color){
echo"Legustael$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
//PHP5
foreach($colorsas&$color){
$color=strtoupper($color);
}
unset($color);/*seaseguradequeescriturassubsiguientesa$color
nomodifiquenelltimoelementodelarrays*/
//Alternativaparaversionesanteriores
foreach($colorsas$key=>$color){
$colors[$key]=strtoupper($color);
}
print_r($colors);
?>

El resultado del ejemplo sera:


Array
(

12 de 22

14/01/17 11:16

PHP: Arrays - Manual


[0]
[1]
[2]
[3]

=>
=>
=>
=>

http://php.net/manual/es/language.types.array.php

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
//llenarunarraycontodoslostemsdeundirectorio
$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"

13 de 22

14/01/17 11:16

PHP: Arrays - Manual

http://php.net/manual/es/language.types.array.php

)
);
//Algunosejemplosquehacenreferenciaalosvaloresdelarrayanterior
echo$fruits["holes"][5];//prints"second"
echo$fruits["fruits"]["a"];//prints"orange"
unset($fruits["holes"][0]);//remove"first"
//Crearunanuevaarraymulti-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;//$arr2hacambiado,
//$arr1siguesiendoarray(2,3)

$arr3=&$arr1;
$arr3[]=4;//ahora$arr1y$arr3soniguales
?>

add a note

User Contributed Notes 20 notes


up
down
37
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) "a"
[-1]=>
string(1) "b"
["+1"]=>
string(1) "c"
["00"]=>

14 de 22

14/01/17 11:16

PHP: Arrays - Manual

http://php.net/manual/es/language.types.array.php

string(1) "d"
["01"]=>
string(1) "e"
["0x1"]=>
string(1) "f"
}
Thus different strings are always mapped to different array keys.

up
down
84
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
23
thomas tulinsky
10 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
20
mathiasgrimm at gmail dot com
2 years ago
<?php
$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

15 de 22

14/01/17 11:16

PHP: Arrays - Manual

http://php.net/manual/es/language.types.array.php

variable: an E_NOTICE-level error message will be issued, and the result will be NULL."

up
down
47
ken underscore yap atsign email dot com
9 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
29
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
40
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
39
lars-phpcomments at ukmix dot net
11 years ago

16 de 22

14/01/17 11:16

PHP: Arrays - Manual

http://php.net/manual/es/language.types.array.php

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
down
20
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
32
ia [AT] zoznam [DOT] sk
11 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).

17 de 22

14/01/17 11:16

PHP: Arrays - Manual

http://php.net/manual/es/language.types.array.php

So either unset $value after each foreach or better use the longer form:
<?php
foreach ( $arr as $key => $value )
{
$arr[ $key ] = 1;
}
?>

up
down
11
note dot php dot lorriman at spamgourmet dot org
3 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
down
20
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/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 );

18 de 22

14/01/17 11:16

PHP: Arrays - Manual

http://php.net/manual/es/language.types.array.php

$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
4
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

19 de 22

14/01/17 11:16

PHP: Arrays - Manual

http://php.net/manual/es/language.types.array.php

4 years ago

up
down
-2
php at markuszeller dot com
7 months ago

up
down
-3
brta dot akos at gmail dot com
3 years ago

up
down
-13
Anonymous
10 years ago

20 de 22

14/01/17 11:16

PHP: Arrays - Manual

http://php.net/manual/es/language.types.array.php

implictions on how associative arrays should be used.

up
down
-17
Spudley
9 years ago

up
down
-12
aditycse at gmail dot com
1 year ago

21 de 22

14/01/17 11:16

PHP: Arrays - Manual

http://php.net/manual/es/language.types.array.php

up
down
-77
carl at linkleaf dot com
9 years ago

add a note

Tipos
Introduccin
Booleanos
Nmeros enteros (Integers)
Nmeros de punto flotante
Cadenas de caracteres (Strings)
Arrays
Objetos
Recursos
NULO
Llamadas de retorno (Callbacks / Callables)
Seudotipos y variables usadas en esta documentacin
Manipulacin de tipos
Copyright 2001-2017 The PHP Group
My PHP.net
Contact
Other PHP.net sites
Mirror sites
Privacy policy

22 de 22

14/01/17 11:16

Das könnte Ihnen auch gefallen