Arrays

1,489 views

Published on

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
1,489
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
20
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Arrays

  1. 1. ArraysUn array (matriz) en PHP es en realidad un mapa ordenado. Un mapa es un tipo dedatos que asocia valores con claves. Este tipo es optimizado para varios usosdiferentes; puede ser usado como una matriz real, una lista (vector), tabla asociativa(caso particular de implementación de un mapa), diccionario, colección, pila, cola yprobablemente más. Ya que los valores de un array pueden ser otros array, también esposible crear árboles y array multidimensionales.Una explicación sobre tales estructuras de datos se encuentra por fuera del propósitode este manual, pero encontrará al menos un ejemplo de cada uno de ellos. Para másinformación, consulte la extensa literatura que existe sobre este amplio tema.SintaxisEspecificación con array()Un valor array puede ser creado por la construcción de lenguaje array(). Ésta toma uncierto número de parejas clave => valor separadas con coma.array( key => value , ... )// key puede ser un integer o string// value puede ser cualquier valor<?php$arr = array("foo" => "bar", 12 => true);echo $arr["foo"]; // barecho $arr[12]; // 1?>Un key puede ser un integer o bien un string. Si una clave es la representaciónestándar de un integer, será interpretada como tal (es decir, "8" será interpretadocomo 8, mientras que "08" será interpretado como "08"). Los valores float en keyserán truncados a valores tipo integer. Los tipos de arrays indexados y asociativos sonel mismo tipo en PHP, el cual pueden contener índices tipo integer o string.Un valor puede ser de cualquier tipo en PHP.Nota:Intentar acceder a un array cuya key no está defina es lo mismo que acceder acualquier otra variable no definida: Se producirá un error de nivel E_NOTICE, y elresultado será NULL.<?php$arr = array("somearray" => array(6 => 5, 13 => 9, "a" => 42));echo $arr["somearray"][6]; // 5echo $arr["somearray"][13]; // 9
  2. 2. echo $arr["somearray"]["a"]; // 42?>Si no especifica una key para un valor dado, entonces es usado el máximo de losíndices integer, y la nueva key será ese valor máximo más 1. Si se especifica una keyque ya tiene un valor asignado, ése valor será sobrescrito.<?php// Este array es lo mismo que...array(5 => 43, 32, 56, "b" => 12);// ...este arrayarray(5 => 43, 6 => 32, 7 => 56, "b" => 12);?> AdvertenciaAntes de PHP 4.3.0, agregar un elemento a un array cuya key máxima actual es unvalor negativo creaba una nueva key como se ha descrito anteriormente. A partir dePHP 4.3.0, la nueva key será 0.Al usar TRUE como key, el valor será evaluado al integer 1. Al usar FALSE como key, elvalor será evaluado al integer0. Al usar NULL como key, el valor será evaluado a unstring vacío. El uso de un string vacío como key creará (o reemplazará) una key con unstring vacío y su valor; no es lo mismo que usar corchetes vacíos.Arrays y objetos no pueden ser usados como keys. Al hacerlo se producirá unaadvertencia: Illegal offset type.Creación/modificación con sintaxis de corchetes cuadradosEs posible modificar un array existente al definir valores explícitamente en él.Esto es posible al asignar valores al array al mismo tiempo que se especifica la keyentre corchetes. También es posible omitir la key, lo que resulta en una pareja decorchetes vacíos ([]).$arr[key] = value;$arr[] = value;// key puede ser un integer o un string// value puede ser cualquier valorSi $arr no existe aun, será creada, así que ésta es también una forma alternativa decrear un array. Para modificar un cierto valor, simplemente asigne un nuevo valor a unelemento usando su key. Para remover una pareja key/valor, use la función unset()sobre ella.<?php$arr = array(5 => 1, 12 => 2);$arr[] = 56; // Esto es igual que $arr[13] = 56;// en este punto del script
  3. 3. $arr["x"] = 42; // Esto agrega un nuevo elemento a la// array con la key "x"unset($arr[5]); // Esto elimina el elemento del arrayunset($arr); // Esto elimina el array completamente?>Nota:Como se mencionó anteriormente, si no se especifica una key, entonces se toma elmáximo de los índices integer existentes, y la nueva key será ese valor máximo más 1.Si no existen índices integer aun, la clave será 0 (cero).Note que el entero máximo usado en la key para este caso no necesita existiractualmente en el array. Tan solo debe haber existido en el array en algún puntodesde que el array haya sido re-indexado. El siguiente ejemplo ilustra este caso:<?php// Crea un array simple.$array = array(1, 2, 3, 4, 5);print_r($array);// Ahora eliminar cada ítem, pero dejar el array mismo intacto:foreach ($array as $i => $value) {unset($array[$i]);}print_r($array);// Agregar un ítem (note que la nueva key 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 sería: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5
  4. 4. ) Array ( ) Array ( [5] => 6 ) Array ( [0] => 6 [1] => 7 )Funciones útilesExiste un buen número de funciones útiles para trabajar con array. Consulte la secciónfunciones de arrays.Nota:La función unset() le permite eliminar keys de un array. Tenga en cuenta que el arrayno es re-indexado. Si desea el comportamiento real de "eliminar y desplazar", el arraypuede ser re-indexado usando la función array_values().<?php$a = array(1 => one, 2 => two, 3 => three);unset($a[2]);/* producirá un array que hubiera sido definida como$a = array(1 => one, 3 => three);y NO$a = array(1 => one, 2 =>three);*/$b = array_values($a);// Ahora $b es array(0 => one, 1 =>three)?>La estructura de control foreach existe específicamente para arrays. Ésta provee unamanera fácil de recorrer un array.Recomendaciones sobre arrays y cosas a evitar¿Por qué es incorrecto $foo[bar]?
  5. 5. Siempre deben usarse comillas alrededor de un índice de array tipo cadena literal. Porejemplo, $foo[bar] es correcto, mientras que $foo[bar] no lo es. ¿Pero por qué? Escomún encontrar este tipo de sintaxis en scripts viejos:<?php$foo[bar] = enemy;echo $foo[bar];// etc?>Esto está mal, pero funciona. La razón es que este código tiene una constanteindefinida (bar) en lugar de un valor string (bar - note las comillas). Puede que en elfuturo PHP defina constantes que, desafortunadamente para tal tipo de código, tenganel mismo nombre. Funciona porque PHP automáticamente convierte una cadena pura(un string sin comillas que no corresponda con símbolo conocido alguno) en un stringque contiene la cadena pura. Por ejemplo, si no se ha definido una constante llamadabar, entonces PHP reemplazará su valor por la cadena bar y usará ésta última.Nota: Esto no quiere decir que siempre haya que usar comillas en la clave. No usecomillas con claves que sean constantes o variables, ya que en tal caso PHP no podráinterpretar sus valores.<?phperror_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 sería:Revisando 0:Notice: Undefined index: $i in /path/to/script.html on line 9Mal:Bien: 1Notice: Undefined index: $i in /path/to/script.html on line 11Mal:Bien: 1Revisando 1:Notice: Undefined index: $i in /path/to/script.html on line 9Mal:Bien: 2Notice: Undefined index: $i in /path/to/script.html on line 11
  6. 6. Mal:Bien: 2Más ejemplos para demostrar este comportamiento:<?php// Mostrar todos los erroreserror_reporting(E_ALL);$arr = array(fruit => apple, veggie => carrot);// Correctoprint $arr[fruit]; // appleprint $arr[veggie]; // carrot// Incorrecto. Esto funciona pero también 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 ahoraprint $arr[fruit]; // appleprint $arr[fruit]; // carrot// Lo siguiente está bien ya que se encuentra al interior de una cadena. Lasconstantes 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 excepción, los corchetes que rodean las matrices al// interior de cadenas permiten el uso de constantesprint "Hello {$arr[fruit]}"; // Hello carrotprint "Hello {$arr[fruit]}"; // Hello apple// Esto no funciona, resulta en un error de intérprete como:// Parse error: parse error, expecting T_STRING or T_VARIABLE or T_NUM_STRING// Esto por supuesto se aplica también al uso de superglobales en cadenasprint "Hello $arr[fruit]";print "Hello $_GET[foo]";// La concatenación es otra opciónprint "Hello " . $arr[fruit]; // Hello apple?>Cuando se habilita error_reporting para mostrar errores de nivel E_NOTICE (como porejemplo definiendo el valor E_ALL), este tipo de usos serán inmediatamente visibles.Por omisión, error_reporting se encuentra configurado para no mostrarlos.
  7. 7. Tal y como se indica en la sección de sintaxis, lo que existe entre los corchetescuadrados ([ y ]) debe ser una expresión. Esto quiere decir que código como elsiguiente funciona:<?phpecho $arr[somefunc($bar)];?>Este es un ejemplo del uso de un valor devuelto por una función como índice del array.PHP también 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 también un identificador válido, asi como bar en el primerejemplo. 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 algún momento en el futuro, puede que el equipo de PHP quiera usar otra constanteo palabra clave, o una constante proveniente de otro código puede interferir. Porejemplo, 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 válido norodear los índices de matriz con comillas, así que "$foo[bar]" es válido. Consulte losejemplos anteriores para más detalles sobre el porqué, así como la sección sobreprocesamiento de variables en cadenas.Conversión a arrayPara cualquiera de los tipos: integer, float, string, boolean y resource, convertir unvalor a un array resulta en un array con un solo elemento, con índice 0, y el valor delescalar que fue convertido. En otras palabras, (array)$scalarValue es exactamente lomismo que array($scalarValue).Si convierte un object a un array, el resultado es un array cuyos elementos son laspropiedados del object. Las keys son los nombres de las variables miembro, conalgunas excepciones notables: las variables privadas tienen el nombre de la clase alcomienzo del nombre de la variable; las variables protegidas tienen un caracter * al
  8. 8. comienzo del nombre de la variable. Estos valores adicionados al inicio tienen bytesnulos a los lados. Esto puede resultar en algunos comportamientos inesperados:<?phpclass A {private $A; // Este campo se convertirá en 0A0A}class B extends A {private $A; // Este campo se convertirá en 0B0Apublic $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 enrealidad una de ellas se llama 0A0A.Si convierte un valor NULL a array, obtiene un array vacío.ComparaciónEs posible comparar arrays con la función array_diff() y mediante operadores dearrays.EjemplosEl tipo matriz en PHP es bastante versátil. Aquí hay algunos ejempos:<?php// Esto:$a = array( color => red,taste => sweet,shape => round,name => apple,4 // 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;
  9. 9. $b[] = c;// Después de que se ejecute el código, $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 #1 Uso de array()<?php// Array como mapa de propiedades$map = array( version => 4,OS => Linux,lang => english,short_tags => true);// Keys estrictamente numéricas$array = array( 7,8,0,156,-10);// esto es lo mismo que array(0 => 7, 1 => 8, ...)$switching = array( 10, // key = 05 => 6,3 => 7,a => 4,11, // key = 6 (el índice entero máximo era 5)8 => 2, // key = 8 (integer!)02 => 77, // key = 020 => 12 // el valor 10 será reemplazado por 12);// array vacío$empty = array();?> Ejemplo #2 Colección<?php$colors = array(rojo, azul, verde, amarillo);foreach ($colors as $color) {echo "¿Le gusta el $color?n";}?>El resultado del ejemplo sería:¿Le gusta el rojo?¿Le gusta el azul?¿Le gusta el verde?¿Le gusta el amarillo?
  10. 10. Modificar los valores del array directamente es posible a partir de PHP 5, pasándolospor referencia. Las versiones anteriores necesitan una solución alternativa: Ejemplo #3 Cambiando elemento en el bucle<?php// PHP 5foreach ($colors as &$color) {$color = strtoupper($color);}unset($color); /* se asegura de que escrituras subsiguientes a $colorno modifiquen el último elemento del arrays */// Alternativa para versiones anterioresforeach ($colors as $key => $color) {$colors[$key] = strtoupper($color);}print_r($colors);?>El resultado del ejemplo sería:Array( [0] => ROJO [1] => AZUL [2] => VERDE [3] => AMARILLO)Este ejemplo crea un array con base uno. Ejemplo #4 Índice con base 1<?php$firstquarter = array(1 => Enero, Febrero, Marzo);print_r($firstquarter);?>El resultado del ejemplo sería:Array( [1] => Enero [2] => Febrero [3] => Marzo) Ejemplo #5 Llenado de un array<?php// llenar un array con todos los ítems de un directorio$handle = opendir(.);while (false !== ($file = readdir($handle))) {$files[] = $file;}
  11. 11. closedir($handle);?>Los Arrays son ordenados. El orden puede ser modificado usando varias funciones deordenado. Vea la sección sobre funciones de arrays para más información. La funcióncount() puede ser usada para contar el número de elementos en un array. Ejemplo #6 Ordenado de un array<?phpsort($files);print_r($files);?>Dado que el valor de un array puede ser cualquier cosa, también puede ser otro array.De esta forma es posible crear arrays recursivas y multi-dimensionales. Ejemplo #7 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 anteriorecho $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 asignación de arrays siempre involucra la copia de valores. Use el operador dereferencia para copiar un array por referencia.<?php$arr1 = array(2, 3);$arr2 = $arr1;$arr2[] = 4; // $arr2 ha cambiado,// $arr1 sigue siendo array(2, 3)
  12. 12. $arr3 = &$arr1;$arr3[] = 4; // ahora $arr1 y $arr3 son iguales?>Objetos Cadenas[edit] Last updated: Fri, 27 Jan 2012 User Contributed NotesArraysAnonymous27-Oct-2011 05:00This is a simple solution for taking previous and next items, even if we are atthe ends of the array.<?php$current_key; // the key of the item we want to search fromif (isset($array[$current_key+1])) {$array_next = $array[$current_key+1]; // get the next item if there is} else {$array_next = $array[0]; // if not take the first (this means this is the end ofthe array)}if (isset($array[$current_key-1])) {$array_prev = $array[$current_key-1]; // get the previous item if there is} else {$array_prev = $array[count($array)-1]; // if not take the last item (this meansthis is the beginning of the array)}?>prince at 3ddatalabs dot com26-Oct-2011 06:02Hi, you also can try goAssocArrayNumeric() on two-dimensional or three-dimensional arrays.<?php//Now its a two-dimensional array$myTwoDimArray =array(a=>array(a0=>apple,a1=>avocado,a2=>apricot),b=>array(b0=>banana,b1=>blackberry,b2=>breadfruit),c=>array(c0=>carrot,c1=>coco,c2=>coffee));echo $myTwoDimArray[0][0]; //wont work! But,
  13. 13. //using the same function used to access associative arrays numerically, we mayaccess 2-dimensional arrays numerically.function goAssocArrayNumeric($arrAssoc, $key=-1){$i = -1;foreach ($arrAssoc as $k => $v){$i++;if($i == $key){return $v;}}return FALSE;}//usage: applying it twice.echo goAssocArrayNumeric(goAssocArrayNumeric($myTwoDimArray,0),0);//appleecho goAssocArrayNumeric(goAssocArrayNumeric($myTwoDimArray,2),1);//cocoecho goAssocArrayNumeric(goAssocArrayNumeric($myTwoDimArray,2),2);//coffee?>Thanks!Prince.prince at 3ddatalabs dot com26-Oct-2011 09:35Hi, heres a way to access an associative array via its numeric index.<?php//sample associative array:$myAssocArray = array(a=>apple, b=>banana, c=>carrot, d=>dragonfruit);echo $assocArray[0];//Above wont work! Because you cant access an associative array numerically.But,function goAssocArrayNumeric($arrAssoc, $key=-1){$i = -1;foreach ($arrAssoc as $k => $v){$i++;if ($i == $key){return $v;}}return FALSE;}//usage:echo goAssocArrayNumeric($myAssocArray,0);//appleecho goAssocArrayNumeric($myAssocArray,3);//dragon fruit?>Hope it helps!Thanks.
  14. 14. Zane MegaLab.it22-Aug-2011 02:10Beware: you cant access an associative array via its numeric index:<?php$a = array(foo => bar,sasfas => addasda,safafsa => hfdhfdf);echo $a[0]; // Undefined index, not bar?>mlvljr20-May-2011 06:37please note that when arrays are copied, the "reference status" of their membersis preserved (http://www.php.net/manual/en/language.references.whatdo.php).abimaelrc10-May-2011 05:15This is another way to get value from a multidimensional array, but for versionsof php >= 5.3.x<?phpfunction array_value_recursive($key, array $arr){$val = null;array_walk_recursive($arr, function($v, $k) use($key, &$val){$val = $k == $key ? $v : (!is_null($val) ? $val : false);});return $val;}$arr = array(foo => foo,bar => array(baz => baz,candy => candy,vegetable => array(carrot => carrot,)),fruits => fruits,);var_dump(array_value_recursive(carrot, $arr)); // string(6) "carrot"var_dump(array_value_recursive(apple, $arr)); // bool(false)var_dump(array_value_recursive(baz, $arr)); // string(3) "baz"var_dump(array_value_recursive(candy, $arr)); // string(5) "candy"var_dump(array_value_recursive(pear, $arr)); // bool(false)?>chris AT cmbuckley DOT co DOT uk30-Apr-2011 04:45Possibly unexpected behaviour:<?php$array = array();var_dump($array[key]); // E_NOTICE (undefined key)$null = null;
  15. 15. var_dump($null[key]); // no E_NOTICE?>Ganpat Thakur07-Apr-2011 10:33I was in need to get value of key which resides at any level in anmultidimensional array. Unfortunately there is no such array function. So Iwrite my own as below...<?phpfunction array_get_key_val($key, $heystack) {if (is_array($heystack)) {foreach ($heystack as $k => $v) {if ($k == $key) {return $v;}elseif (is_array($v)) {return array_get_key_val($key, $v);}}}return FALSE;}?>Hope this will help to few.anhsang9x at gmail dot com25-Mar-2011 06:09Im want to save values in array and display its, can to simple way:<?php$arr1 = array();//begin array$index = 0;//arrays index$value_return = array();//Values me needfor($i = 0; $i<10; $i++){$arr1[$i] = rand(10, 100);//use to be function random for get values from 10 to100.if($arr1[$i]%2 == 0)//Get values me need.{$value_return[$index] = $arr1[$i];//save values in this array$index += 1;//get space save for index.}}//display result.foreach($value_return as $value_display)echo "</br>".$value_display."</br>";print_r($arr1);?>lemurjan at gmail dot com10-Mar-2011 04:54Sometimes you may need an array of constants including concatenated strings.
  16. 16. That works fine in this case:<?phpdefine("GLUE", "&");function array_to_string($a) {$r = "";foreach ($a as $key => $value) { $r .= "$key => $value<br>"; };return $r;}// DECLARING ARRAY (1)$array = array("one", "two", "one".GLUE."two");echo array_to_string($array);?>This seems rather strange behavior in a CLASS nevertheless:<?phpclass wrong_class {// DECLARING ARRAY (2)private $array = array("one", "two", "one".GLUE."two");function __toString() {return array_to_string($this->array);}}$wc = new wrong_class();echo $wc;/*Parse error: parse error, expecting `) in ... code on line 21*/?>Anyway, if you force this declaring method inside a CLASS, you could change theobject map directly:<?phpclass proper_class {function __construct() {// DECLARING ARRAY (3)$this->array = array("one", "two", "one".GLUE."two");}function __toString() {return array_to_string($this->array);}}$pc = new proper_class();echo $pc;?>falkon303 at gmail dot com30-Jan-2011 01:08Multidimensional arrays work great for checking search options if they exist ina $_GET string. The following saved me a lot of time.<?php
  17. 17. $advanced_option[color] = array("red", "blue", "green");$advanced_option[state] = array("new", "broken");$advanced_option[state] = array("on","off");foreach($advanced_option as $y => $advanced_option[$y]){// HERE WARE ARE GOING INTO EACH ARRAYS VALUES/ITEMS$sub_array = $advanced_option[$y];foreach($sub_array as $z => $sub_array[$z]){// IF THE SEARCH OPTI0N EXISTS IN THE GET STRING, SET AN ARRAY NAMED AFTER THATVALUE TO BE CHECKED (FOR CHECKBOXES & RADIOBUTTONS)if ($_GET[$y] == $advanced_option[$y][$z]){$checked[$advanced_option[$y][$z]] = "checked";}}}?>Anonymous23-Nov-2010 02:27In case you had to get an element from a function-returned array without havingto save the array to a variable, heres a workaround Ive come up with.<?php$stuff = something random here;// To get the first element in the array, use resetecho reset(explode( , $stuff));// Returns "something"// To get the last element, use endecho end(explode( , $stuff));// Returns "here"// For an in-between element, you can use array_search on the flipped array$i = 1; //key for the elementecho array_search($i, array_flip(explode( , $stuff)));// Returns "random"?>Flappi28220-Aug-2010 10:03Heres a simple function I wrote to remove a value from an array, without leavinga hole:<?phpfunction removeFromArray(&$array, $key){foreach($array as $j=>$i){if($i == $key){$array = array_values(unset($array[$j]));return true;break;}}?>
  18. 18. Returns true on success, or false on failure. The array will be automaticallyupdatedWalter Tross12-Aug-2010 11:04It is true that "array assignment always involves value copying", but the copyis a "lazy copy". This means that the data of the two variables occupy the samememory 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.ivegner at yandex dot ru22-Jul-2010 04:20Like in Perl, you can use curly braces ({}) instead of square brackets ([]) toaccess array members:<?php$a = array ();$a[7] = seven;$a{hello} = world;print $a{7} . . $a[hello];?>Prints seven world.william at cycronsystems dot com09-Jun-2010 04:28I couldnt find a way to Trim an array in PHP so i wrote this little functionthat seemed to do the trick. It will trim the array down to a specified size<?php//Utility Function to Trim Arrayfunction trim_array(array $array,$int){$newArray = array();for($i=0; $i<$int; $i++){array_push($newArray,$array[$i]);}return (array)$newArray;}?>Example:var_dump($treatList);array(3) {["id"]=>string(3) "476"["categoryID"]=>string(2) "49"["title"]=>string(55) "80% off Sidewalk Crawling Classes from Urban Adventures"$treatList = trim_array($listist,2);Will result in:var_dump($treatList);array(2) {["id"]=>string(3) "476"
  19. 19. ["categoryID"]=>string(2) "49"zachera03-Jun-2010 12:39function array_closest_key($needle,$haystack){foreach($haystack as $key => $value){if($needle <= $value){return $key;}}}Get the closest key to the specified $needle out of $haystack.dtomasiewicz at gmail dot com12-May-2010 10:42<?php/*** Functions for examining and manipulating matrices (n-dimensional arrays) ofdata* with string dot-separated paths. For example, you might do this withmultidimensional* array:* $var = $array[someKey][cats][dogs][potato];** Accomplishing this can be a nightmare if you dont know the depth of the pathor the array* is of a variable dimension.** You can accomplish the same by using $array as a Matrix:* $array = new Matrix($array);* $var = $array->get(someKey.cats.dogs.potato);** @author Daniel Tomasiewicz <www.fourstaples.com>*/class Matrix {private $data;public function __construct(array $data = array()) {$this->data = $data;}/*** Gets the value at the specified path.*/public function get($path = null) {if($path === null) {return $this->data;}$segs = explode(., $path);$target =& $this->data;for($i = 0; $i < count($segs)-1; $i++) {if(isset($target[$segs[$i]]) && is_array($target[$segs[$i]])) {$target =& $target[$segs[$i]];} else {return null;
  20. 20. }}if(isset($target[$segs[count($segs)-1]])) {return $target[$segs[count($segs)-1]];} else {return null;}}/*** Sets a value to a specified path. If the provided value is* null, the existing value at the path will be unset.*/public function set($path, $value = null) {if(is_array($path)) {foreach($path as $p => $v) {$this->set($p, $v);}} else {$segs = explode(., $path);$target =& $this->data;for($i = 0; $i < count($segs)-1; $i++) {if(!isset($target[$segs[$i]])) {$target[$segs[$i]] = array();}$target =& $target[$segs[$i]];}if($segs[count($segs)-1] == *) {foreach($target as $key => $value) {$target[$key];}} elseif($value === null && isset($target[$segs[count($segs)-1]])) {unset($target[$segs[count($segs)-1]]);} else {$target[$segs[count($segs)-1]] = $value;}}}/*** Returns a flattened version of the data (one-dimensional array* with dot-separated paths as its keys).*/public function flatten($path = null) {$data = $this->get($path);if($path === null) {$path = ;} else {$path .= .;}
  21. 21. $flat = array();foreach($data as $key => $value) {if(is_array($value)) {$flat += $this->flatten($path.$key);} else {$flat[$path.$key] = $value;}}return $flat;}/*** Expands a flattened array to an n-dimensional matrix.*/public static function expand($flat) {$matrix = new Matrix();foreach($flat as $key => $value) {$matrix->set($key, $value);}return $matrix;}}?>john at nowhere dot com18-Dec-2009 09:33If you ever wondered if you can do something like:<?php$a = function_that_returns_an_array()[some_index][some_other_index] ;?>The answer is no, you cant. But you can use the following function. I named iti() because its a short name and stands for "to index".<?php/*** Usage: i( $array, $index [, $index2, $index3 ...] )** This is functionally equivalent to $array[$index1][$index2][$index3]...** It can replace the more prolix** $tmp = some_function_that_returns_an_array() ;* $value = $tmp[some_index][some_other_index] ;** by doing the job with a single line of code as in** $value = i( some_function_that_returns_an_array(), some_index,some_other_index ) ;*
  22. 22. * Note that since this function is slower than direct indexing, it should onlybe used in cases like the one* described above, for improving legibility.** @param $array* @param $index* @param [optional] $index2, index3, ...* @throws Exception when the indexes do not exist*/function i(){$args = func_get_args();$array = $args[0];//gets the fist parameter, $array$indexes = $args;unset($indexes[0]);//because indexes[0] is actually not an index, but the firstparameter, $arrayforeach( $indexes as $index ){if( (! is_array($array)) || (! array_key_exists( $index, $array )) ){throw new Exception("Array index out of bounds.Parameters:".print_r($args,true));}$array = $array[$index];}return $array;}?>aaron at tekserve dot com24-Oct-2009 06:16Heres a function to recursively convert objects to arrays and remove thespecial characters from private and protected variables. I use it withXML_Serializer to convert objects to XML.<?phpfunction object_to_array($mixed) {if(is_object($mixed)) $mixed = (array) $mixed;if(is_array($mixed)) {$new = array();foreach($mixed as $key => $val) {$key = preg_replace("/^0(.*)0/","",$key);$new[$key] = object_to_array($val);}}else $new = $mixed;return $new;}?>unix at bujanoci dot net20-Oct-2009 10:55Just in case someone finds it usefull.If you want to capitalize the first letter of each word in the array you could:<?php$myarray = array("one","two","three","four","etc..");$map = array_map(ucfirst, $myarray);$j = join( , , $map);echo $j;
  23. 23. ?>This will return: One , Two , Three , Four , Etc..Probably its not worth of posting it, but just thought beginners might find itusefull.Anonymous02-Oct-2009 04:33This is a modification of a function like this which works with two dimensionalarrays. Pass a 2d array to this function and my function will return an array ofthe arrays with the specified key-value pair (specified by $key and $value).<?phpfunction seekKey($array, $key, $value){$ret = array();for ($i=0;$i<count($array);$i++){if ($array[$i][$key]==$value)$ret[] = $array[$i];}return $ret;}?>Martin28-Sep-2009 11:04You can actually create arrays in arrays; just consider the following code:<?phpfunction LoadData($file){$lines = file($file) or die(Could not open file);foreach($lines as $line){$i[] = array($line);print_r($i[1])}LoadData(file.csv);?>A (.csv-)file is loaded into the function LoadData and stored in the array$lines. Then foreach puts the values from the $lines-array into $line and $i isdefined as an array of the array $line. Please note that this type of code couldtake up much of CPU-usage; it generates a multi-dimensional array.When $i is printed (in the example, value 1 of the array) it would display:Array ( [0] => Array ([0] => 7;75;X;0;0;1;0;3;Gr;Br;Do;0;0;0;0;0;0;0;0;[1] => ;200;K;0;0;0;0;0;Gr;0;0;0;0;ZL;0;0;0;0;0;[2] => ;260;Z;;;;;;Gr;;;;;VL;;;;;;[3] => ;270;K;;;;1;;Gr;Br;Li;;;;;;;;;[4] => ;500;V;;;;;;Br;;;;;;;;;;;[5] => 6;60;X;;;;;;;;;;;;;;;;;[6] => ;80;K;;;;;;Gr;;;;;ZL;;;;;;[7] => ;210;Z;;;;;;Gr;;;;;;;;;;;)
  24. 24. webmaster at oehoeboeroe dot nl04-May-2009 07:47A simple function to check if you can use your variable as an array offsetvalidly and without getting it typecasted.<?phpfunction is_safe_offset($offset) {return array_pop(@array_flip(array($offset => 0))) === $offset;}$a = 8;var_dump(is_safe_offset($a)); // true$b = 8;var_dump(is_safe_offset($b)); // false$c = 08;var_dump(is_safe_offset($c)); // true$d = foo;var_dump(is_safe_offset($d)); // true$e = 3.8;var_dump(is_safe_offset($e)); // false$f = false;var_dump(is_safe_offset($f)); // false$g = null;var_dump(is_safe_offset($g)); // false$h = array();var_dump(is_safe_offset($h)); // false$i = new StdClass;var_dump(is_safe_offset($i)); // false?>genix at arctoz dot de07-Mar-2009 04:41Hello,to check if an element was set is actually pretty simple:<?php$array = (first => 1,sec => 2);$out = (isset($array[third])) ? $array[third] : third not set...;echo $out;?>greets,genixDawid Krysiak17-Dec-2008 03:09
  25. 25. Trying to get array element that was not set, throws ERROR_NOTICE and returnsNULL. Example:<?php /* php v.4.4.7 */$array = array(apple => green,orange => orange,);$pear_color = $array[pear]; // Notice: Undefined index: pear in/path/to/file.php on line 123var_dump($pear_color); // NULL?>Havent found that mentioned on this page.hek at theeks dot net24-Oct-2008 08:58Note that NULL is not exactly a scalar value, so the following two lines of codedo NOT produce identical arrays.<?php$x = (array) null; // $x ends up an empty array (zero elements)$y = array(null); // $y ends up an array containing one element (a null)?>pinkgothic at gmail dot com13-Sep-2008 08:49Re: fmouse,the phenomenom youre describing pertains to superglobals, not arrays, and itonly applies in a very specific scope. Check outhttp://de.php.net/manual/en/language.variables.variable.php :"Please note that variable variables cannot be used with PHPs Superglobalarrays within functions or class methods. The variable $this is also a specialvariable that cannot be referenced dynamically."frywater04-Jun-2008 04:43> fmouseVariable variables can be used with arrays as discussed in the variable variablesection.Also, from your code, $somevar can be an array and still work fine.$fum = "somevar";$$fum = array(); // $somevar is now an array$foo = $$fum;print_r( $foo); // we get an empty array printedprint_r() doesnt just print arrays, it prints any variable type.If you pass it a variable, that hasnt been defined yet, it wont know how toprint it.You would get this same results by passing any undefined variable such as:print_r( $bar ); // PHP Notice: undefined variable ...$barfmouse at fmp dot com29-Apr-2008 01:14Using variables as array names no longer works in PHP5.$fum = "somevar";$foo = $$fum;# Still works if $somevar isnt an array. $foo contains the value of $somevar
  26. 26. but ....$fum = "_POST";print_r($$fum);print_r(${$fum});Neither form of indirection works in this context. $$fum comes back empty.If you have PHP4 code that used this kind of indirection you can work around thechange in PHP5 using an eval().$fum = "_POST";$foo = eval("return $$fum;");print_r($foo);This works!rama dot devi at gmail dot com18-Mar-2008 01:52Sorting double dimensional arrays by a specified key bothe for Strings and forintegers:Ex:$personDetails = array( array("firstName" => "Nancy", "lastName" => "Grace","age" => 22), array("firstName" => "Andy", "lastName" => "Peter", "age" => 28),array("firstName" => "Jim", "lastName" => "Gary", "age" => 25),array("firstName" => "Lary", "lastName" => "James", "age" => 28),array("firstName" => "Peter", "lastName" => "David", "age" => 17),array("firstName" => "Raj", "lastName" => "King", "age" => 9), array("firstName"=> "John", "lastName" => "Baxter","age" => 35) );//To sort the array by firstName:-function sortFirstName($p1, $p2) {return strnatcmp($p1[firstName], $p2[firstName]);}usort($personDetails, sortFirstName);//To sort by an integer Fieldfunction sortByInteger(&$personDetails, $field) {$sort = "return strnatcmp($p1[$field], $p2[$field]);";usort($personDetails, create_function($p1,$p2, $sort));return $personDetails;}$personDetails = sortByInteger($personDetails, age);//To sort the array in Descending order by a key, It can be done by adding "-"sign before strnatcmp() function.I hope this helpsken underscore yap atsign email dot com09-Jan-2008 08:00"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 thatreturns an array of values on success or NULL if nothing found.$values = search(...);
  27. 27. Now you want to merge the array with another array. What do we do if $values isNULL? No problem:$combined = array_merge((array)$values, $other);Voila.pepesantillan at gmail dot com18-Dec-2007 04:25z on 22-Apr-2005 12:10 wrote:-----------------------------------------------Heres a simple function to insert a value into some position in an array<?phpfunction array_insert($array,$pos,$val){$array2 = array_splice($array,$pos);$array[] = $val;$array = array_merge($array,$array2);return $array;}?>and now for example...<?php$a = array("John","Paul","Peter");$a = array_insert($a,1,"Mike");?>Now $a will be "John","Mike","Paul","Peter"-----------------------------------------------Im learning to use PHP and reading about array_splice found that<?phpfunction array_insert($array,$pos,$val){$array2 = array_splice($array,$pos);$array[] = $val;$array = array_merge($array,$array2);return $array;}$a = array("John","Paul","Peter");$a = array_insert($a,1,"Mike");print_r($a);?>would output the same as<?php$b = array("John","Paul","Peter");array_splice($b,1,0,array("Mike"));
  28. 28. print_r($b);?>SID TRIVEDI10-Oct-2007 02:14<?php//Simple Login Script using associative array.//You may modify the codes and use $_POST[FORM_FIELD_DATA] for your web-page.//You may spice-up the codes with more form field validation & securityfeatures.//$user_name=$_POST[user_name];//$password=$_POST[password];$test_user_name = michelle_smith; //for testing purpose only$test_password = msmith321; //for testing purpose only$user_name = $test_user_name;$password = $test_password;// here user_name is key and password is the value of an array..// website owner has to add new user/site member manually in $login_array$login_array = array(user_name => password,alex_duff => alx321,xena78 => xena321,dela_pena => delp321,shawn_1981 => shw81,michelle_smith => msmith321);ksort ($login_array);reset($login_array);if (isset($login_array[$user_name])){$pass_check = $login_array[$user_name];if ($password === $pass_check){echo "Welcome, $user_name!n<br>"; //may redirect to specific webpage.}else{echo "Please try again!"; //may redirect to Error page.}}else{echo "Please register with us. Thanks!"; //may redirect to registration page.exit();}echo("n<br>");echo Thanks to Thies C. Arntzen, Stig Bakken, Shane Caraveo, Andi Gutmans,Rasmus Lerdorf, Sam Ruby, Sascha Schumann, Zeev Suraski, Jim Winstead, AndreiZmievski for wonderful PHP!;
  29. 29. ?>carl at linkleaf dot com06-Sep-2007 11:36Its worth noting that there does not appear to be any functional limitations onthe length or content of string indexes. The string indexes for your arrays cancontain 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 andcould cost you lots of extra CPU time. However, if you have to use a long stringas an array index you wont have to worry about the length or content.Gautam30-Aug-2007 01:56<?php//EXAMPLE of Multi-Dimentional Array where as an arrays keys are an arrayitself.//Its so easy to create one like this.$movie_to_watch = array (Action=>array(Kanu Reeves => Matrix Reloaded,Pearce Brosnan => Die Another Day,Tom Cruz => Mission Impossible,Jason Statham => Crank,Danzel Washington => Man on Fire),Comedy =>array (Charlie Chaplin => City Lights,Jim Carrey => Cable Guy,Rowan Atkinson => The Ultimate Disaster));$type_wanted = Action; //You may switch type from Action to Comedy.$hero_wanted = Pearce Brosnan; // You may switch hero from Pearce Brosnan toJim Carrey.print ("$hero_wanted s $type_wanted movie is " .$movie_to_watch[$type_wanted][$hero_wanted].".");// produces browser output as under:// Pearce Brosnan s Action movie is Die Another Day.?>Olegk, getmequick[at]gmail[dot]com21-Aug-2007 02:59Hey..
  30. 30. here is a function which helps to avoid using empty/issetcheckings for arrays.(its acts simillar to default modifier in Smarty)Using this function you will avoid Undefined index orUndefined offset error.<?php$_POST[id][other] = val1;/*key exist (same as $_POST[id][other])*/echo getRequestParam(id[other], default value);/*key doesnt exist, we get default value (same as $_POST[var])*/echo getRequestParam(var, default value);function getRequestParam( $var, $default = , $method = post ){preg_match_all(!(w+)!i,$var, $match );array_shift($match);$_vars = $match[0];$ret = null;if( strtoupper($method) == POST ) {$ret = _findRequestParam($_vars, $_POST);}elseif( strtoupper($method) == GET ) {$ret = _findRequestParam($_vars, $_GET);}elseif( strtoupper($method) == COOKIE ) {$ret = _findRequestParam($_vars, $_COOKIE);}elseif( strtoupper($method) == SESSION ) {$ret = _findRequestParam($_vars, $_SESSION);}if (! $ret )return $default;elsereturn $ret;}/**@access private*/
  31. 31. function _findRequestParam($vars, $find_in , $curr_key = 0){static $ret;if( array_key_exists($vars[$curr_key], $find_in) ) {if( count( $vars)-1 == $curr_key ) {$ret = $find_in[$vars[$curr_key]];}elseif( $curr_key < count( $vars)-1 ) {_findRequestParam( $vars, $find_in[$vars[$curr_key]], $curr_key+1 );}}return $ret;}?>Hope this will help someone!conorj14-Jul-2007 08:34Another note on unquoted array indices. Because it is first interpreted as aconstant, it must obey the naming convention of constants. i.e. a letter orunderscore followed by optional letter, digit and/or underscore characters.Therefore while the following array declaration is legal:$a = array(1st=>First,2nd=>Second);Trying to access either array item as follows causes an error:$first = "$a[1st]";$second = "$a[2nd]";moehbass at gmail dot com10-Jul-2007 05:41< b>Mark Gukov</b> wrote below:Regarding the fact that theres no need to quote arrays keys when enclosed indouble quotes: it only applies to single dimensional arrays.The following works fine:<?php$r[a] = apple;echo "$r[a] is tasty.";?>...but in the case of multi-dimensional arrays:<?php$r[a][b] = banana;echo "$r[a][b] is tasty.";?>would result in "Array[c] is tasty."-----------------------------------------------------------------
  32. 32. However, the following runs fine;$r[a][b] = banana;echo "{$r[a][b]} is tasty.";Just box it!don dot hosek at gmail dot com23-May-2007 05:37Its slightly faster to use array_splice to remove an element of an array:array_splice($array, $index, 1)than to do it using the suggested method of unset and reindex:unset($array[$index]);$array = array_values($array);The difference, however, is very small. With 950 iterations I had times ofunset and reindex: 0.22837495803833splice: 0.22392416000366lesantoso at yahoo dot com20-Mar-2007 02:14This Indonesian number speller function is twicefaster(*) than the one provided in class Terbilang byanghuda(at)gmail(dot)com (25-May-2006 08:52):http://www.lesantoso.com/terbilang.html(*) 2.1 vs. 4.2 seconds in processing 10000 random numbersSpudley16-Mar-2007 01:44On array recursion...Given the following code:< ?$myarray = array(test,123);$myarray[] = &$myarray;print_r($myarray);?>The print_r() will display *RECURSION* when it gets to the third element of thearray.There doesnt appear to be any other way to scan an array for recursivereferences, so if you need to check for them, youll have to use print_r() withits second parameter to capture the output and look for the word *RECURSION*.Its not an elegant solution, but its the only one Ive found, so I hope ithelps someone.kal at kalunite dot com i mean dot net16-Jan-2007 05:55About the automatic conversion of bare strings...My opinion is that it never should have been implemented. Isnt it easier to NOTimplement this "handy" feature in the first place? It is such a convenient wayfor "smart" programmers to write unsafe, not-futureproof code. Please removethis feature from future versions of PHP, please. (Hey, if you could change theOOP mechanisms between PHP 4 and PHP 5, why cant you make this change, right?)25-Oct-2006 09:18This page should include details about how associative arrays are implemenedinside PHP; e.g. using hash-maps or b-trees.This has important implictions on the permance characteristics of associative
  33. 33. arrays and how they should be used; e.g. b-tree are slow to insert but handlecollisions better than hashmaps. Hashmaps are faster if there are no collisions,but are slower to retrieve when there are collisions. These factors haveimplictions on how associative arrays should be used.Mark Gukov27-Sep-2006 02:18Regarding the fact that theres no need to quote arrays keys when enclosed indouble quotes: it only applies to single dimensional arrays.The following works fine:<?php$r[a] = apple;echo "$r[a] is tasty.";?>...but in the case of multi-dimensional arrays:<?php$r[a][b] = banana;echo "$r[a][b] is tasty.";?>would result in "Array[c] is tasty."petruzanautico at yahoo dot com dot ar21-Sep-2006 08:30Regarding the message of phoenixbytes:The line foreach($bad as $baddies); will just yield in $baddies the last valueof the array $bad.I think that wasnt your intention, in that case there are faster and betterways than foreach.I think what you wanted to do is:<?phpforeach($bad as $baddies) // make a collection{if (preg_match("/$baddies/i", $mailto)) // find a match{$addrmail = "false";}else{$addrmail = "true";}} // foreach end?>php dot net at todandlorna dot com25-Jul-2006 04:28in response to ch dot martin at gmail dot comIf you are using the following code:<?php$r = array(05 => "abc", 35 => "def");foreach ($r as $key=>$value)var_dump($key);?>
  34. 34. and you need the array key 35 to be a string (for looping maybe), you can makesure the key is a string by appending a 0 on the front.035 instead of 35ch dot martin at gmail dot com08-Jun-2006 11:40Extremely irritating quirk regarding the variable types of array keys:<?php$r = array(05 => "abc", 35 => "def");foreach ($r as $key=>$value)var_dump($key);?>The first var_dump for 05 is:string(2) "05"as expected. But the second, 35, turns out as:int(35)Php apparently decided to make the 35 became an int, but not the 05 (presumablybecause it leads with a zero). As far as I can see, there is absolutely no wayof making string(2) "35" an array key.anghuda(at)gmail(dot)com25-May-2006 06:52this is simpler tha function display_angka_bilangan by ktaufik(at)gmail(dot)com(16-Feb-2005 12:40)< ?/*** Class : Terbilang* Spell quantity numbers in Indonesian or Malay Language*** author: huda m elmatsani* 21 September 2004* freeware** example:* $bilangan = new Terbilang;* echo $bilangan -> eja(137);* result: seratus tiga puluh tujuh***/Class Terbilang {function terbilang() {$this->dasar = array(1=>satu,dua,tiga,empat,lima,enam,tujuh,delapan,sembilan);$this->angka = array(1000000000,1000000,1000,100,10,1);$this->satuan = array(milyar,juta,ribu,ratus,puluh,);}
  35. 35. function eja($n) {$i=0;while($n!=0){$count = (int)($n/$this->angka[$i]);if($count>=10) $str .= $this->eja($count). " ".$this->satuan[$i]." ";else if($count > 0 && $count < 10)$str .= $this->dasar[$count] . " ".$this->satuan[$i]." ";$n -= $this->angka[$i] * $count;$i++;}$str = preg_replace("/satu puluh (w+)/i","1 belas",$str);$str = preg_replace("/satu (ribu|ratus|puluh|belas)/i","se1",$str);return $str;}}?>benjcarson at digitaljunkies dot ca09-May-2006 01:46phoenixbytes: The regex you have posted for matching email addresses isincorrect. Among other things, it does not allow + before the @ (which isperfectly valid and can be quite useful to separate extensions of a singleaddress). RFC 822 [1] defines the grammar for valid email addresses, and (theextemely long) regex implementing can be found at [2]. Even the "Add Note" pagehere at php.net says:[quote]And if youre posting an example of validating email addresses, please dontbother. Your example is almost certainly wrong for some small subset of cases.See this information from OReilly Mastering Regular Expressions book for thegory details.[/quote]A note to others: please do your homework before writing another email-matchingregex.[1] http://www.ietf.org/rfc/rfc0822.txt?number=822[2] http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html.phoenixbytes at o2 dot co dot uk16-Apr-2006 05:10i use the array() function for deciding upon an email addresss validity, i havea wap stalker of my site that loves to exploit every hole i leave, so i usedthe following script to avoid being email bombed with my own file sender script,the array() is used to filter out undesirable email providers and, of course,any and all of my own addresses. before all that i used a REGEX to make sureits an actual email address before going any further.$mailto = "mail.domain.org"; // the input to be testedif (preg_match("/^[A-Z0-9._%-]+@[A-Z0-9._%-]+.[A-Z]{2,6}$/i", $mailto)) // seeif its really an email address
  36. 36. {$bad = array(mytrashmail.com, mymail.ro, acasa.ro, gala.net,phoenixbytes); // pick out the victimsforeach($bad as $baddies); // make a collectionif (preg_match("/$baddies/i", $mailto)) // find a match{$addrmail = "false";}else{$addrmail = "true";}}else{$addrmail = "false";}$addrmail can then be used in an argument.$baddies can be used to give a list, if necessary.i hope this helps someone.crozzer01-Apr-2006 12:54Passing variables into the array constructor:Just a NOOB pointer, I couldnt find other examples for this. If you want topass the value of an existing variable into the array() constructor, you canquote it or not, both methods are valid.< ?$foo_value = foo string;$bar_value = bar string;$myArray = array(foo_key => $foo_value, // not quotedbar_key => "$bar_value"); // quotedforeach ($myArray as $k => $v) {echo "$myArray[$k] => $v.<br />n";}?>Both of these will work as expected, but the unqoted $foo_value method above ismarginally faster because adding quotes adds an additional string de-reference.sales at maboom dot ch13-Dec-2005 09:41if you need to check a multidimensonal array for values its handy to store itlike$ar[key1][0]$ar[key2][0]$ar[key3][0]$ar[key1][1]$ar[key2][1]
  37. 37. $ar[key3][1]and to loop the keys.Fill the array (from a database-request):while($rf=mysql_fetch_row($rs)){$nr=$rf[0];$channel[nr][$nr]=$rf[1];$channel[chatter][$nr]=$rf[2];}Call the values:foreach(array_keys($channel[nr]) as $test){print nr:.$test.<br>;print value nr: .$channel[nr][$test].<br>;print chatter: .$channel[chatter][$test].<br>;}This is useful, if you have to look later for an elementinside the array:if(in_array($new_value,$channel[nr])) print do something.;Hope this helps someone.ia [AT] zoznam [DOT] sk30-Sep-2005 02:55Regarding the previous comment, beware of the fact that reference to the lastvalue of the array remains stored in $value after the foreach:<?phpforeach ( $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 inthe 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:<?phpforeach ( $arr as $key => $value ){
  38. 38. $arr[ $key ] = 1;}?>stochnagara at hotmail dot com27-Sep-2005 01:53Regarding the previous comment, thw following code does the job:<?phpforeach($arr as $key => &$value) {$value = 1;}?>jazepstein OverAt GeeMail dot com19-Sep-2005 06:14Regarding the previous comment, the fact that this code has no effect isperfectly expected:<?phpforeach($arr as $value) {$value = 1;}?>The reason that this doesnt work, is because each time that PHP goes throughthe loop, it _copies_ the value of the array element into $value. So if youassign a new value to the data in $value, it has no effect on the actual array,because you only changed the value of the copy that was put in $value.As was discovered in the previous post, the only way to get around this problemis to change the value in the original array. Hence, a typical foreach shouldinstead look like this:<?phpforeach($arr as $key => $value) {$arr[$key] = 1;}?>caifara aaaat im dooaat be28-Aug-2005 02:28[Editors note: You can achieve what youre looking for by referencing $single,rather than copying it by value in your foreach statement. Seehttp://php.net/foreach for more details.]Dont know if this is known or not, but it did eat some of my time and maybe itwont eat your time now...I tried to add something to a multidimensional array, but that didnt work atfirst, 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 ;
  39. 39. }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 printsArray([0] => Array([a] => 0[b] => 1[c] => 3)[1] => Array([aa] => 0[bb] => 11[c] => 3))*/?>uzakufuklar at hotmail dot com03-Aug-2005 11:24It is a kind of simple muti-dimensional array list.I have made it just to give a simple idea.<?phpecho "Here well see how to create a multi-dimensional array.n";$a=array(fruits=>array(a=>orange,b=>grape,c=>apple),numbers=>array(1,2,3,4,5,6),holes=>array(first,5=>second,third));foreach($a as $list=>$things){
  40. 40. foreach($things as $newlist=>$counter){echo $counter;}}?>z22-Apr-2005 12:10Heres a simple function to insert a value into some position in an array<?phpfunction array_insert($array,$pos,$val){$array2 = array_splice($array,$pos);$array[] = $val;$array = array_merge($array,$array2);return $array;}?>and now for example...<?php$a = array("John","Paul","Peter");$a = array_insert($a,1,"Mike");?>Now $a will be "John","Mike","Paul","Peter"jeff splat codedread splot com21-Apr-2005 09:16Beware that if youre using strings as indices in the $_POST array, that periodsare transformed into underscores:< html>< body><?phpprintf("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 )roland dot swingler at transversal dot com05-Apr-2005 08:24Something that tripped me up:If you mix string and integer keys, be careful if you are doing a comparison onthe to find if a string key exists.For example, this will not do what you expect it to do:<?php$exampleArray = array();
  41. 41. $exampleArray[foo] = bar;$exampleArray[] = Will create 0 index;$keyWeAreLookingFor = "correctKey";foreach ($exampleArray as $key => $value){if ($key == $keyWeAreLookingFor){print "Found Key";}}?>It will print "Found Key", because (I presume) when PHP makes the comparisonbetween the string "correctKey" and the index 0, it casts the string to aninteger, rather than casting 0 to the string "0" and then doing the comparison.Using === fixes the problem:<?phpforeach ($exampleArray as $key => $value){if ($key === $keyWeAreLookingFor){print "Found Key";}}?>lars-phpcomments at ukmix dot net28-Mar-2005 08:40Used 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 dont need to array_merge if its just one range:<?php$array = range(A, Z);?>mortoray at ecircle-ag dot com16-Feb-2005 12:59On array copying a deep copy is done of elements except those elements which arereferences, in which case the reference is maintained. This is a very importantthing to understand if you intend on mixing references and recursive arrays.By Example:$a = array( 1 );$aref_a = array( &$a );$copy_aref_a = $aref_a;$acopy_a = array( $a );$copy_acopy_a = $acopy_a;$a[] = 5;$acopy_a[0][] = 6;
  42. 42. print_r( $aref_a ); //Shows: ( (1,5) )print_r( $copy_aref_a ); //Shows: ( (1,5) )print_r( $acopy_a ); //Shows: ( (1, 6) )print_r( $copy_acopy_a ); //Shows: ( (1) )ktaufik(at)gmail(dot)com16-Feb-2005 12:40For you who works for localized "say" number to letter ( ex , 7=> seven,8=>eight) for Bahasa Indonesia.Indonesia "say" or "Terbilang" is based on 3 digit number.thousands, millions and trillions .... will be based on the 3 digit number.In Indonesia you say 137 as "Seratus Tiga Puluh Tujuh"<?php//build random 3 digit number to be "said" in Bahasa Indonesia$x=rand(0,9);$y=rand(0,9);$z=rand(0,9);function display_angka_bilangan($n) {$angka = array(1 => satu,2 => dua,3 => tiga,4 => empat,5 => "lima",6 => enam,7 => tujuh,8 => delapan,9 => sembilan);return $angka[$n];}// Terbilang X-------Say Xif ($x==1){$terbilangx="seratus ";}elseif ($x==0){$terbilangx=;}else {$terbilangx=.display_angka_bilangan($x). .ratus ;}// Terbilang Y ------Say Yif ($y==0){$terbilangy=;}elseif ($y==1 && $z==1){$terbilangy="sebelas";$terbilangz=;}elseif ($y==1 && $z==0){$terbilangy="sepuluh ";$terbilangz=;}elseif ($y==1 && $z!==1 && $z!==0){$terbilangy=.display_angka_bilangan($z).belas ;}else {$terbilangy=.display_angka_bilangan($y). .puluh ;}// Terbilang z ------Say zif ($z==0){$terbilangz="";}elseif ($z==0 && $y==1){$terbilangz="";}elseif ($z==1 && $y==1){$terbilangz="";}elseif($y==0) {$terbilangz="".display_angka_bilangan($z);}elseif ($y==1 && $z!==1 && $z!==0) {$terbilangz="";}else {$terbilangz="".display_angka_bilangan($z);};$terbilang=$terbilangx.$terbilangy.$terbilangz;echo $x.$y.$z." ";
  43. 43. echo $terbilang;?>Hope it is usefulktaufik(at)gmail(dot)comdb05-Jan-2005 07:06[Editors Note: (Second example.) These are not "arrays in arrays". These aresingle-dimensional arrays containing stdClass objects; all objects arereferenced by default in PHP5. You can see in the var_dump output that theypoint to the same object.]Attention with Arrays in Arrays!If you copy (=) an array which contains arrays it will be REFERENCED not COPIED.Example:<?php/* GOOD ONE */echo "<b>Here copy (=) works correct:</b><br>";/* Initialise Array 1 */$x1 = array(array(10,20),array(30,40));/* COPY Array */$x2 = $x1;/* Change some values in Array 2 */$x2[0][0]=77;$x2[1][1]=99;echo "<b>Original:</b><pre>";var_dump($x1);echo "</pre><b>Changed Copy:</b><pre>";var_dump($x2);/* BAAAAAAAD ONE */echo "</pre><hr><b>Here copy (=) FAILS:</b><br>";/* Initialise Array 1 */$a1[0]->bla[0]->id=10;$a1[0]->bla[1]->id=20;$a1[1]->bla[0]->id=30;$a1[1]->bla[1]->id=40;/* COPY Array */$a2 = $a1;/* Change some values in Array 2 (!) */$a2[0]->bla[0]->id=77;$a2[1]->bla[1]->id=99;echo "<b>Original:</b><pre>";var_dump($a1);echo "</pre><b>Changed Copy:</b><pre>";var_dump($a2);echo "</pre>";php?>The output of $a1 and $a2 will be the same..Joe Morrison <jdm at powerframe dot com>08-Nov-2004 01:26
  44. 44. Programmers new to PHP may find the following surprising:<?php$x[1] = foo;$x[0] = bar;echo "Original array:n";var_dump($x);array_pop($x);echo "Array after popping last element:n";var_dump($x);?>The surprise is that element 0 is deleted, not element 1. Apparently the notionof "last element" has more to do with how the array is stored internally thanwith which element has the highest numeric index. I recently translated a Perlprogram to PHP and was bitten by this one.My solution was to identify all the places in my code where I could prove thatthe array elements were assigned sequentially. In those cases it is safe to usearray_pop, array_splice, etc. since the array indices correspond with the arraylayout. For the other cases, my solution was to write replacements for thebuilt-in array functions such as this one:<?phpfunction safe_pop(&$a){if (!isset($a))return;if (!is_array($a))return;if (count($a) == 0)return;unset($a[max(array_keys($a))]);}?>Cameron Brown18-Nov-2003 08:51Negative and positive array indices have different behavior when it comes tostring<->int conversion. 1 and "1" are treated as identical indices, -1 and "-1"are not. So:$arr["1"] and $arr[1] refer to the same element.$arr["-1"] and $arr[-1] refer to different elements.The following code:< ?$arr[1] = "blue";
  45. 45. $arr["1"] = "red";$arr[-1] = "blue";$arr["-1"] = "red";var_dump($arr);?>produces the output:array(3) {[1]=>string(3) "red"[-1]=>string(4) "blue"["-1"]=>string(3) "red"}This code should create an array with either two or four elements. Which oneshould be the "correct" behavior is an exercise left to the reader....akamai at veloxmail dot com dot br16-Jul-2003 04:22It is quite simple, but dont forget when youll using foreach with formsarrays.If your field name is:< input type="checkbox" name="foo[bar][]" ...It doesnt work.This should work:< input type="checkbox" name="foo[bar][]" ...agape_logos at shaw dot ca11-Jul-2003 04:59I was having trouble getting javascript arrays and php arrays to work togetherwith a Check All checkboxe. Here is a simple solution. Clicking the Check Allcheckbox will check all checkboxes on the form.< script language="JavaScript">function chkAll(frm, arr, mark) {for (i = 0; i <= frm.elements.length; i++) {try{if(frm.elements[i].name == arr) {frm.elements[i].checked = mark;}} catch(er) {}}}< /script>< form name=foo>< input type="checkbox" name="ca" value="1" onClick="chkAll(this.form,formVar[chkValue][], this.checked)"><?phpfor($i = 0; $i < 5; $i++){echo("<input type=checkbox name=formVar[chkValue][] value=$i>");}?>
  46. 46. </form>Dean M.chroniton .at. gmx .dot. li26-Mar-2003 10:13I didnt find this anywhere in the docs and i think it is worth a mention:$a[] = &$a;print_r($a);// will output:/*Array([0] => Array*RECURSION*)*/// this means that $a[0] is a reference to $a ( that is detected by print_r() ).I guess this is what the manual calls recursive arrays.07-Mar-2003 03:28"Using NULL as a key will evaluate to an empty string. Using an emptry string askey will create (or overwrite) a key with an empty string and its value, it isnot the same as using empty brackets."If you create an array like this:$foo = array(null => bar);And then want to access bar, you must use this syntax:echo $foo[]; // notice the two single quotesThis will of course cause a fatal error:echo $foo[];wmoranATpotentialtechDOTcom29-Nov-2002 03:10Dereferencing arrays takes some time, but is not terribly expensive.I wrote two dummy loops to test performance:for ($i =0; $i < count($a); $i++) {$x = $a[$b[$i]];$y = $a[$b[$i]];$z = $a[$b[$i]];}for ($i =0; $i < count($a); $i++) {$q = $b[$i];$x = $a[$q];$y = $a[$q];$z = $a[$q];}The first loop is 6.5% slower than the second. Meaning that dereferencing arraysis not terribly expensive, unless you do it a whole lot. I would expect thateach extra reference costs about 3% in speed. The lesson is that if youre goingto be using a specific value in an array for a number of operations, you cangain a little speed by assigning it to a temp variable (or creating a referencewith $q = &$b[$i]) but its not worth getting crazy over.
  47. 47. I tested this with iterations of 10,000 and 100,000 on php 4.2 and the resultswere consistent.mu at despammed dot com14-Oct-2002 11:50Recursive arrays and multi-dimensional arrays are the same thing and completelyidentical.The following confirms this:$fruits1["european"]["green"] = "Apple";$fruits2 = array ( "european" => array ( "green" => "Apple"));print ($fruits1 === $fruits2);Result: 1 (= true)hramrach_L at centrum. cz ;-)11-Jun-2002 05:40Arrays can be merged using + as discussed in the notes for array_merge.http://www.php.net/manual/en/function.array-merge.phpphilip at boone dot at24-May-2002 06:06For all of you having problems when using php arrays in an HTML form input fieldname, and wanting to validate the form using javascript for example, it is mucheasier to specify an id for the field as well, and use this id for validation.Example:< input type="text" id="lastname" name="fields[lastname]">then in the javascript check:if(formname.lastname.value == "") {alert("please enter a lastname!");}This works very well. If you have any problems with it, let me know.

×