La Verdad Del Arrays

También podría gustarte

Está en la página 1de 33

Arrays

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


que asocia valores con claves. Este tipo es optimizado para varios usos diferentes;
puede ser usado como una matriz real, una lista (vector), una tabla asociativa (una
implementacin de un mapa), diccionario, coleccin, pila, cola, y posiblemente
ms. Ya que los valores de un array pueden ser otros arrays, rboles y tambin
son posibles arrays multidimensionales.
Una explicacin sobre tales estructuras de datos est fuera del alcance de este
manual, pero encontrar 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 usando el constructor del lenguaje array(). ste toma
un cierto nmero de parejasclave => valor como argumentos.
array(
clave

=> valor,

clave2 => valor2,


clave3 => valor3,
...
)

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 [].

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, 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.

Ejemplo #2 Ejemplo de moldeado 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 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);
?>

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 integer ms grande 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) "foo"
[1]=>
string(3) "bar"
[2]=>
string(5) "hello"
[3]=>
string(5) "world"
}

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

El resultado del ejemplo sera:


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

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,

"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 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

Si $arr an no existe, se crear, as que esto es tambin una forma alternativa de


crear un array. Sin embargo, esta prctica es desaconsejada ya que si $arr ya
contiene algn valor (p.ej. un string de una variable de peticin), entonces este
valor 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 con su clave. Para quitar un par clave/valor, se debe llamar la
funcin unset() en 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);

// Esto elimina el array completo

?>

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

El resultado del ejemplo sera:


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

Funciones tiles

Hay un buen 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')
?>

La estructura de control foreach existe especficamente para arrays. sta provee


una manera fcil de recorrer unarray.

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 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";
}
?>

El resultado del ejemplo sera:


Revisando 0:
Notice: Undefined index:

$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

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 'veggie
'
// es asignado a una constante llamada fruit.
define('fruit', 'veggie');
// Note la diferencia ahora
print $arr['fruit'];

// apple

print $arr[fruit];

// carrot

// Lo siguiente est bien ya que se encuentra al interior de una cadena.


Las constantes no son procesadas al
// interior de cadenas, as que no se produce un error E_NOTICE aqu
print "Hello $arr[fruit]";

// Hello apple

// Con una 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_NUM_
STRING'
// Esto por supuesto se aplica tambin al uso de superglobales en cadenas
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 valorE_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 array resulta en un array con un solo elemento, con ndice 0, y el valor
del escalar que fue convertido. En otras palabras,(array)$scalarValue es
exactamente lo mismo que array($scalarValue).
Si convierte un object a un array, el resultado es un array cuyos elementos son las
propiedades del object. Las claves son los nombres de las variables miembro, con

algunas excepciones notables: las variables privadas tienen el nombre de la clase


al comienzo del nombre de la variable; las variables protegidas tienen un caracter
'*' al comienzo del nombre de la variable. Estos valores adicionados al inicio tienen
bytes nulos a los lados. Esto puede resultar en algunos comportamientos
inesperados:
<?php
class 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' => 'red',

'taste' => 'sweet',


'shape' => 'round',
'name'
4

=> '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'
).
?>

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(

10, // key = 0
5

=>

6,

=>

7,

'a'

=>

4,
11, // key = 6 (el ndice entero mximo era 5

)
'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 gusta el rojo?
Le gusta el azul?
Le gusta el verde?
Le gusta el 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] => ROJO
[1] => AZUL
[2] => VERDE
[3] => 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 anterior
echo $fruits["holes"][5];

// prints "second"

echo $fruits["fruits"]["a"]; // prints "orange"


unset($fruits["holes"][0]);

// remove "first"

// Crear una nueva array multi-dimensional


$juices["apple"]["green"] = "good";
?>

La asignacin de arrays siempre involucra la copia de valores. Use el operador de


referencia para copiar un arraypor 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 24 notes


up
down
69
mlvljr
3 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
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

$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 (nonhashtable) 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
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

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

ianodebe at yahoo dot com...

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.

The solution is to cast it to a string first, like this


$array[(string) $stringableObject]

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.

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

In my tests, both in_array and array_key_exists exhibited the same order


of growth.

up
down
-1
Ray.Paseur often uses Gmail
7 months ago

Array-to-String conversion by assignment or by using an array in a string


context gives a string of data that contains only the word, 'Array' and
this data substitution often occurs silently. This happens because the
standard PHP installation suppresses Notice-level messages, and the
array-to-string conversion, even though it causes data loss, is only
considered a Notice condition. Here is how to discern what PHP is doing.
http://php.net/manual/en/language.types.array.php
http://php.net/manual/en/language.types.string.php#language.types.string.
casting
<?php // demo/array_to_string.php
/**
* Starting with the default standard error-level of E_ALL ~ E_NOTICE
* OUTPUTS:
* Array
*/
$xyz = array('X', 'Y', 'Z');
echo $xyz;
/**
* Setting the error-level of E_ALL causes Notice messages to appear
* OUTPUTS:
* Notice: Array to string conversion in /path/to/demo/array_to_string.php
on line XXX
* Array
*/
error_reporting(E_ALL);
$xyz = array('X', 'Y', 'Z');
echo $xyz;

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.

También podría gustarte