Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
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.
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);
?>
"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);
?>
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"]);
?>
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;
Nota:
=>
=>
=>
=>
=>
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:
$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.
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";
}
?>
$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
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";
?>
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
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; //
}
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
array();
= 'a';
= 'b';
= 'c';
a 5)
5
3
'a'
=>
=>
=>
10, // key = 0
6,
7,
4,
11, // key = 6 (el ndice entero mximo er
);
// array vaco
$empty = array();
?>
Ejemplo #9 Coleccin
<?php
$colors = array('rojo', 'azul', 'verde', 'amarillo');
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);
?>
=>
=>
=>
=>
ROJO
AZUL
VERDE
AMARILLO
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"
);
// 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";
?>
"a"
"b"
"c"
"d"
["01"]=>
string(1) "e"
["0x1"]=>
string(1) "f"
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
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
up
down
38
lars-phpcomments at ukmix dot net
Used to creating arrays like this in Perl?
11 years ago
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
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
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.
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
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
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.
<?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