Documentos de Académico
Documentos de Profesional
Documentos de Cultura
La Verdad Del Arrays
La Verdad Del Arrays
La Verdad Del Arrays
Sintaxis
Especificacin con array()
Un array puede ser creado usando el constructor del lenguaje array(). ste toma
un cierto nmero de parejasclave => valor como argumentos.
array(
clave
=> valor,
La coma despus del ltimo elemento del array es opcional y se puede 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 comnmente, ya que permite la adicin sencilla de nuevos
elementos al final.
A partir de PHP 5.4 tambin se puede usar la sintaxis de array corta, que
reemplaza array() con [].
La clave puede ser un integer o un string. El valor puede ser de cualquier tipo.
Adems, los siguientes moldeados de tipo en la clave producir:
o Strings que contienen integers vlidos sern moldeados a el tipo integer.
P.e.j. 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 Floats tambin sern moldeados en integers, lo que significa que la parte
fraccionaria se elimina. P.e.j. la clave 8.7 en realidad ser almacenada
como 8.
o Bools son moldeados a integers, tambin, p.e.j. la clave true en realidad
ser almacenada como 1 y la clavefalse como 0.
o Null ser moldeado a un string vaco, p.e.j. la clave null en realidad ser
almacenada como "".
o Arrays y objects no pueden ser usados como claves. Si lo hace, dar lugar
a una advertencia: Illegal offset type.
Si varios elementos en la declaracin del array usan la misma clave, slo la ltima
ser usada y los dems son sobrescritos.
=> "a",
"1"
=> "b",
1.5
=> "c",
Como todas las claves en el ejemplo anterior se convierten en 1, los valores sern
sobrescritos en cada nuevo elemento y el ltimo valor asignado "d" es el nico que
queda.
Los arrays 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);
?>
Es posible especificar la clave slo para algunos de los elementos y dejar por
fuera a los dems:
Ejemplo #5 Claves no en todos los elementos
<?php
$array = array(
"a",
"b",
6 => "c",
"d",
);
var_dump($array);
?>
Como se puede ver el ltimo valor "d" se le asign la clave 7. Esto es debido a que
la mayor clave integer 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 array
<?php
$array = array(
"foo" => "bar",
42
=> 24,
Nota:
Tanto los corchetes como las llaves pueden ser utilizadas de forma indiferente para
acceder a elementos de un array (p.ej.: $array[42] y $array{42} harn lo mismo 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:
Si intenta acceder a una clave del array que no se ha definido es lo mismo que el
acceso a cualquier otra variable no definida: se emitir un mensaje de error de
nivel E_NOTICE, y el resultado ser NULL.
Creacin/modificacin con sintaxis de corchete
Un array existente puede ser modificado al definir valores explcitamente en ste.
Esto se realiza mediante la asignacin de valores al array, especificando la clave
en corchetes. La clave tambin se puede omitir, resultando en un par de corchetes
vacos ([]).
$arr[clave] = valor;
$arr[] = valor;
// clave puede ser un integer o string
// valor puede ser cualquier valor de cualquier tipo
?>
Nota:
Como se mencion anteriormente, si no se especifica una clave, se toma el
mximo de los ndices integerexistentes, y la nueva clave ser ese valor mximo
ms 1 (aunque al menos 0). Si todava no existen ndicesinteger, la clave
ser 0 (cero).
Tenga en cuenta que la clave integer mxima utilizada para ste no es necesario
que actualmente exista en elarray. 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);
?>
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 funcinarray_values().
<?php
$a = array(1 => 'uno', 2 => 'dos', 3 => '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')
?>
Esto est mal, pero funciona. La razn es que este cdigo tiene una constante
indefinida (bar) en lugar de unstring ('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 stringpuro. Por ejemplo, si no se ha definido
una constante llamada bar, entonces PHP reemplazar su valor por elstring '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";
}
?>
$i in /path/to/script.html on line 9
Mal:
Bien: 1
Notice: Undefined index:
Mal:
$i in /path/to/script.html on line 11
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
// apple
// 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
// Hello apple
// Hello carrot
// Hello apple
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]
?>
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";
?>
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
}
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' => 'red',
=> '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 = array();
$b[] = 'a';
$b[] = 'b';
$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'
).
?>
=> 4,
'OS'
=> 'Linux',
'lang'
=> 'english',
);
// Keys estrictamente numricas
$array = array( 7,
8,
0,
156,
-10
);
// esto es lo mismo que array(0 => 7, 1 => 8, ...)
$switching = array(
10, // key = 0
5
=>
6,
=>
7,
'a'
=>
4,
11, // key = 6 (el ndice entero mximo era 5
)
'8'
=>
2, // key = 8 (integer!)
=> 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";
}
?>
print_r($firstquarter);
?>
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 (
"first",
5 => "second",
"third"
)
);
// Algunos ejemplos que hacen referencia a los valores del array anterior
echo $fruits["holes"][5];
// prints "second"
// remove "first"
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
7
mathiasgrimm at gmail dot com
4 months 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 variable: an E_NOTICE-level error
message will be issued, and the result will be NULL."
up
down
9
note dot php dot lorriman at spamgourmet dot org
1 year ago
There is another kind of array (php>=
5.3.0) produced by
up
down
46
ken underscore yap atsign email dot com
7 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
32
chris at ocportal dot com
Note that array value buckets are reference-safe, even through
serialization.
1 year ago
<?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
46
jeff splat codedread splot com
9 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
35
ia [AT] zoznam [DOT] sk
9 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
29
lars-phpcomments at ukmix dot net
9 years ago
up
down
14
ivegner at yandex dot ru
1 year 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
27
caifara aaaat im dooaat be
9 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
down
0
malay89space at gmail dot com
In response to
1 day ago
<?php
$q = array("How many states are there in Nigeria:",
"What is the capital city of Anambra state:",
"What year was Nigeria amalgamated:"
);
$a = array(
array(20, 39, 36, 40),
array( "Awka", "Aniocha", "Ogidi", "Owerri"),
array( "1940", "1914", "1960", "1941")
);
$cq = count($q);
// No. of elements in question array...
$ca = count($a);
// No. of elements in answer array...
$j = 0;
// denotes the key of nested array elements of ans
array...
for( $i=0; $i<$cq; $i++)
//traversing thro elements of que array...
{
echo ($i+1).". ".$q[$i]."?...<br>";
foreach($a[$j] as $value )
// traversing thro nested array
elements of ans array...
{
echo "\t".$value."<br>";
}
$j++;
/* incermenting the key of subsequent nested arrays of
ans arrays outside foreach
so that in increments with each que array element...
*/
}
?>
up
down
-2
martijntje at martijnotto dot nl
2 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.
up
down
-5
Spudley
7 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
-5
Anonymous
8 years ago
This page should include details about how associative arrays are
implemened inside PHP; e.g. using hash-maps or b-trees.
up
down
-10
cromney at pointslope dot com
2 years ago
One thing to be careful of is making any assumptions about the underlying
implementation with respect to performance. For example, the
documentation talks about hash-maps, which might lead you to expect O(1)
key lookups.
<?php
function find_val($n) {
$t = array();
$last = null;
for ($x = 0; $x < $n; $x++) {
$last = "" . $x;
$t[] = $last;
}
var_dump(in_array($last, $t));
}
function find_key($n) {
$t = array();
$last = null;
for ($x = 0; $x < $n; $x++) {
$last = "" . $x;
$t[$last] = true;
}
var_dump(array_key_exists($last, $t));
}
$n = 1600000;
find_val($n);
// Time taken: 1123ms
find_key($n);
// Time taken: 803
/*
Additional Timings:
n
100000
200000
400000
800000
1600000
*/
?>
find_val(ms)
99
169
301
570
1123
find_key(ms)
82
130
217
416
803
up
down
-1
Ray.Paseur often uses Gmail
7 months ago
up
down
-9
harry at ddtechnologies dot com
PHP array_diff_assoc() Function
You can compare the keys and values of two arrays, and return the
differences:
<?php
$a1=array("red","green","blue","yellow");
$a2=array("red","green","blue");
$result=array_diff_assoc($a1,$a2);
print_r($result);
1 year ago
?>
http://www.show-ip.org
up
down
-14
Walter Tross
4 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
-24
gtisza at gmail dot com
2 years ago
Be very careful when using a result as an array. <?php echo $a['foo']
['bar']['baz'] ?> will throw an error if $a is an object, and throw a
warning if $a is an array but does not have the right keys, but it will
silently return true if $a is null or boolean or int, and if $a is a
string, it will return its first character. (This is true even with
E_STRICT set.) This can be a major gotcha with functions which return
null or false if they are unsuccessful.
up
down
-9
brta dot akos at gmail dot com
1 year 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
-60
carl at linkleaf dot com
7 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.
up
down
-11
ianodebe at yahoo dot com
Pls I am having issues with this //
$questions = array("How many states are there in Nigeria",
"What is the capital city of Anambra state",
"What year was Nigeria amalgamated"
);
$answers = array(
array(20, 39, 36, 40),
array( "Awka", "Aniocha", "Ogidi", "Owerri"),
array( "1940", "1914", "1960", "1941")
);
how can i print the data in this form ..
1. How many states are there in your country
21
59
36
4 months ago
30
2. What is the capital city of Anambra state Awka
Aniocha
Ogidi
Owerri
3. What year was Nigeria amalgamated 1940
1914
1960
1941
up
down
-13
ffe
<?php
1 year ago
error_reporting(E_ALL);
$res=42;
echo("+".$res[0]."+".$res[10]."+");
$res[0]=1;
?>
The last line correctly states "Warning: Cannot use a scalar value as an
array", but the echo produces +++ as output with no warning. This seems
strange to me.
up
down
-52
azuleta at eycambiental dot com
1 year ago
I think there's a mistake in the las example:
...'<?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
?>'
I think it should be: ...'ahora $arr2 y $arr3 son iguales'...
Thanks.