Using variables as array names no longer works in PHP5.
$fum = "somevar";
$foo = $$fum;
# Still works if $somevar isn't an array. $foo contains the value of $somevar
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 the change in PHP5 using an eval().
$fum = "_POST";
$foo = eval("return $$fum;");
print_r($foo);
This works!
Matrices
Una matriz en PHP es en realidad un mapa ordenado. Un mapa es un tipo de datos que asocia valores con claves. Este tipo es optimizado en varias formas, de modo que puede usarlo como una matriz real, o una lista (vector), tabla asociativa (caso particular de implementación de un mapa), diccionario, colección, pila, cola y probablemente más. Ya que puede tener otra matriz PHP como valor, es realmente fácil simular árboles.
Una explicación sobre tales estructuras de datos se encuentra por fuera del propósito de este manual, pero encontrará al menos un ejemplo de cada uno de ellos. Para más información, le referimos a literatura externa sobre este amplio tema.
Sintaxis
Especificación con array()
Un array puede ser creado por la construcción de lenguaje array(). Ésta toma un cierto número de parejas clave => valor separadas con coma.
array( clave => valor , ... ) // clave puede ser un integer o string // valor puede ser cualquier valor
<?php
$matriz = array("foo" => "bar", 12 => true);
echo $matriz["foo"]; // bar
echo $matriz[12]; // 1
?>
Una clave puede ser un integer o un string. Si una clave es la representación estándar de un integer, será interpretada como tal (es decir, "8" será interpretado como 8, mientras que "08" será interpretado como "08"). Los valores flotantes en clave serán truncados a valores tipo integer. No existen tipos diferentes para matrices indexadas y asociativas en PHP; sólo existe un tipo de matriz, el cual puede contener índices tipo entero o cadena.
Un valor puede ser de cualquier tipo en PHP.
<?php
$matriz = array("unamatriz" => array(6 => 5, 13 => 9, "a" => 42));
echo $matriz["unamatriz"][6]; // 5
echo $matriz["unamatriz"][13]; // 9
echo $matriz["unamatriz"]["a"]; // 42
?>
Si no especifica una clave para un valor dado, entonces es usado el máximo de los índices enteros, y la nueva clave será ese valor máximo + 1. Si especifica una clave que ya tiene un valor asignado, ése valor será sobrescrito.
<?php
// Esta matriz es la misma que ...
array(5 => 43, 32, 56, "b" => 12);
// ...esta matriz
array(5 => 43, 6 => 32, 7 => 56, "b" => 12);
?>
A partir de PHP 4.3.0, el comportamiento de generación de índices descrito ha cambiado. Ahora, si agrega un elemento a una matriz cuya clave máxima actual es un valor negativo, entonces la siguiente clave creada será cero (0). Anteriormente, el nuevo índice hubiera sido establecido a la clave mayor existente + 1, al igual que con los índices positivos.
Al usar TRUE como clave, el valor será evaluado al integer 1. Al usar FALSE como clave, el valor será evaluado al integer 0. Al usar NULL como clave, el valor será evaluado a una cadena vacía. El uso de una cadena vacía como clave creará (o reemplazará) una clave con la cadena vacía y su valor; no es lo mismo que usar corchetes vacíos.
No es posible usar matrices u objetos como claves. Al hacerlo se producirá una advertencia: Illegal offset type.
Creación/modificación con sintaxis de corchetes cuadrados
Es posible modificar una matriz existente al definir valores explícitamente en ella.
Esto es posible al asignar valores a la matriz al mismo tiempo que se especifica la clave entre corchetes. También es posible omitir la clave, agregar una pareja vacía de corchetes ("[]") al nombre de la variable en ese caso.
$matriz[clave] = valor; $matriz[] = valor; // clave puede ser un integer o string // valor puede ser cualquier valorSi $matriz no existe aun, ésta será creada. De modo que esta es también una forma alternativa de especificar una matriz. Para modificar un cierto valor, simplemente asigne un nuevo valor a un elemento especificado con su clave. Si desea remover una pareja clave/valor, necesita eliminarla mediante unset().
<?php
$matriz = array(5 => 1, 12 => 2);
$matriz[] = 56; // Esto es igual que $matriz[13] = 56;
// en este punto del script
$matriz["x"] = 42; // Esto agrega un nuevo elemento a la
// matriz con la clave "x"
unset($matriz[5]); // Esto elimina el elemento de la matriz
unset($matriz); // Esto elimina la matriz completa
?>
Note: Como se menciona anteriormente, si provee los corchetes sin ninguna clave especificada, entonces se toma el máximo de los índices enteros existentes, y la nueva clave será ese valor máximo + 1. Si no existen índices enteros aun, la clave será 0 (cero). Si especifica una clave que ya tenía un valor asignado, el valor será reemplazado.
WarningA partir de PHP 4.3.0, el comportamiento de generación de índices descrito ha cambiado. Ahora, si agrega un elemento al final de una matriz en la que la clave máxima actual es negativa, la siguiente clave creada será cero (0). Anteriormente, el nuevo índice hubiera sido definido como la mayor clave + 1, al igual que ocurre con los índices positivos.
Note que la clave entera máxima usada para este caso no necesita existir actualmente en la matriz. Tan solo debe haber existido en la matriz en algún punto desde que la matriz haya sido re-indexada. El siguiente ejemplo ilustra este caso:
<?php
// Crear una matriz simple.
$matriz = array(1, 2, 3, 4, 5);
print_r($matriz);
// Ahora eliminar cada ítem, pero dejar la matriz misma intacta:
foreach ($matriz as $i => $valor) {
unset($matriz[$i]);
}
print_r($matriz);
// Agregar un ítem (note que la nueva clave es 5, en lugar de 0 como
// podría esperarse).
$matriz[] = 6;
print_r($matriz);
// Re-indexar:
$matriz = array_values($matriz);
$matriz[] = 7;
print_r($matriz);
?>El resultado del ejemplo seria:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 ) Array ( ) Array ( [5] => 6 ) Array ( [0] => 6 [1] => 7 )
Funciones útiles
Existe un buen número de funciones útiles para trabajar con matrices. Consulte la sección funciones de matrices.
Note: La función unset() le permite remover la definición de claves de una matriz. Tenga en cuenta que la matriz NO es re-indexada. Si sólo usa "índices enteros comunes" (comenzando desde cero, incrementando en uno), puede conseguir el efecto de re-indexación usando array_values().
<?php
$a = array(1 => 'uno', 2 => 'dos', 3 => 'tres');
unset($a[2]);
/* producirá una matriz que hubiera sido definida 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 específicamente para las matrices. Ésta provee una manera fácil de recorrer una matriz.
Recomendaciones sobre matrices y cosas a evitar
¿Porqué es incorrecto $foo[bar]?
Siempre deben usarse comillas alrededor de un índice de matriz tipo cadena literal. Por ejemplo, use $foo['bar'] y no $foo[bar]. ¿Pero qué está mal en $foo[bar]? Es posible que haya visto la siguiente sintaxis en scripts viejos:
<?php
$foo[bar] = 'enemigo';
echo $foo[bar];
// etc
?>
Note: Esto no quiere decir que siempre haya que usar comillas en la clave. No querrá usar comillas con claves que sean constantes o variables, ya que en tal caso PHP no podrá interpretar sus valores.
El resultado del ejemplo seria:<?php
error_reporting(E_ALL);
ini_set('display_errors', true);
ini_set('html_errors', false);
// Matriz simple:
$matriz = array(1, 2);
$conteo = count($matriz);
for ($i = 0; $i < $conteo; $i++) {
echo "\nRevisando $i: \n";
echo "Mal: " . $matriz['$i'] . "\n";
echo "Bien: " . $matriz[$i] . "\n";
echo "Mal: {$matriz['$i']}\n";
echo "Bien: {$matriz[$i]}\n";
}
?>
Revisando 0: Notice: Undefined index: $i in /path/to/script.html on line 9 Mal: Bien: 1 Notice: Undefined index: $i in /path/to/script.html on line 11 Mal: 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
Más ejemplos para demostrar este hecho:
<?php
// Mostrar todos los errores
error_reporting(E_ALL);
$matriz = array('fruta' => 'manzana', 'vegetal' => 'zanahoria');
// Correcto
print $matriz['fruta']; // manzana
print $matriz['vegetal']; // zanahoria
// Incorrecto. Esto funciona pero también genera un error de PHP de
// nivel E_NOTICE ya que no hay definida una constante llamada fruta
//
// Notice: Use of undefined constant fruta - assumed 'fruta' in...
print $matriz[fruta]; // manzana
// Definamos una constante para demostrar lo que pasa. Asignaremos el
// valor 'vegetal' a una constante llamada fruta.
define('fruta', 'vegetal');
// Note la diferencia ahora
print $matriz['fruta']; // manzana
print $matriz[fruta]; // zanahoria
// 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 "Hola $matriz[fruta]"; // Hola manzana
// Con una excepción, los corchetes que rodean las matrices al
// interior de cadenas permiten el uso de constantes
print "Hola {$matriz[fruta]}"; // Hola zanahoria
print "Hola {$matriz['fruta']}"; // Hola manzana
// 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 se aplica también al uso de superglobales en cadenas, por supuesto
print "Hola $matriz['fruta']";
print "Hola $_GET['foo']";
// La concatenación es otra opción
print "Hola " . $matriz['fruta']; // Hola manzana
?>
Cuando habilita error_reporting() para mostrar errores de nivel E_NOTICE (como por ejemplo definiendo el valor E_ALL) verá estos errores. Por defecto, error_reporting se encuentra configurado para no mostrarlos.
Tal y como se indica en la sección de sintaxis, debe existir una expresión entre los corchetes cuadrados ('[' y ']'). Eso quiere decir que puede escribir cosas como esta:
<?php
echo $matriz[alguna_funcion($bar)];
?>
<?php
$descripciones_de_error[E_ERROR] = "Un error fatal ha ocurrido";
$descripciones_de_error[E_WARNING] = "PHP produjo una advertencia";
$descripciones_de_error[E_NOTICE] = "Esta es una noticia informal";
?>
<?php
$descripciones_de_error[1] = "Un error fatal ha ocurrido";
$descripciones_de_error[2] = "PHP produjo una advertencia";
$descripciones_de_error[8] = "Esta es una noticia informal";
?>
Tal y como lo hemos explicado en los anteriores ejemplos, $foo[bar] aun funciona pero está mal. Funciona, porque debido a su sintaxis, se espera que bar sea una expresión constante. Sin embargo, en este caso no existe una constante con el nombre bar. PHP asume ahora que usted quiso decir bar literalmente, como la cadena "bar", pero que olvidó escribir las comillas.
¿Entonces porqué está mal?
En algún momento en el futuro, el equipo de PHP puede querer usar otra constante o palabra clave, o puede que usted introduzca otra constante en su aplicación, y entonces se ve en problemas. Por ejemplo, en este momento no puede usar las palabras empty y default de esta forma, ya que son palabras clave reservadas especiales.
Note: Reiterando, al interior de un valor string entre comillas dobles, es válido no rodear los índices de matriz con comillas, así que "$foo[bar]" es válido. Consulte los ejemplos anteriores para más detalles sobre el porqué, asi como la sección sobre procesamiento de variables en cadenas.
Conversión a matriz
Para cualquiera de los tipos: integer, float, string, boolean y resource, si convierte un valor a un array, obtiene una matriz con un elemento (con índice 0), el cual es el valor escalar con el que inició.
Si convierte un object a una matriz, obtiene las propiedades (variables miembro) de ese objeto como los elementos de la matriz. 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 comportamiento inesperado.
<?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());
?>
Si convierte un valor NULL a matriz, obtiene una matriz vacía.
Comparación
Es posible comparar matrices con array_diff() y mediante operadores de matriz.
Ejemplos
El tipo matriz en PHP es bastante versátil, así que aquí se presentan algunos ejemplos que demuestran el poder completo de las matrices.
<?php
// esto
$a = array( 'color' => 'rojo',
'sabor' => 'dulce',
'forma' => 'redonda',
'nombre' => 'manzana',
4 // la clave será 0
);
// es completamente equivalente a
$a['color'] = 'rojo';
$a['sabor'] = 'dulce';
$a['forma'] = 'redonda';
$a['nombre'] = 'manzana';
$a[] = 4; // la clave será 0
$b[] = 'a';
$b[] = 'b';
$b[] = 'c';
// resultará en la matriz array(0 => 'a' , 1 => 'b' , 2 => 'c'),
// o simplemente array('a', 'b', 'c')
?>
Example #1 Uso de array()
<?php
// Array como mapa de propiedades
$mapa = array( 'versión' => 4,
'SO' => 'Linux',
'idioma => 'inglés',
'etiquetas_cortas' => true
);
// claves estrictamente numéricas
$matriz = array( 7,
8,
0,
156,
-10
);
// esto es lo mismo que array(0 => 7, 1 => 8, ...)
$cambios = array( 10, // clave = 0
5 => 6,
3 => 7,
'a' => 4,
11, // clave = 6 (el índice entero máximo era 5)
'8' => 2, // clave = 8 (¡entero!)
'02' => 77, // clave = '02
0 => 12 // el valor 10 será reemplazado por 12
);
// matriz vacía
$vacio = array();
?>
Example #2 Colección
<?php
$colores = array('rojo', 'azul', 'verde', 'amarillo');
foreach ($colores as $color) {
echo "¿Le gusta el $color?\n";
}
?>
El resultado del ejemplo seria:
¿Le gusta el rojo? ¿Le gusta el azul? ¿Le gusta el verde? ¿Le gusta el amarillo?
Modificar los valores de la matriz directamente es posible a partir de PHP 5, pasándolos por referencia. Las versiones anteriores necesitan una solución alternativa:
Example #3 Colección
<?php
// PHP 5
foreach ($colores as &$color) {
$color = strtoupper($color);
}
unset($color); /* se asegura de que escrituras subsiguientes a $color
no modifiquen el último elemento de la matriz */
// Alternativa para versiones anteriores
foreach ($colores as $clave => $color) {
$colores[$clave] = strtoupper($color);
}
print_r($colores);
?>
El resultado del ejemplo seria:
Array ( [0] => ROJO [1] => AZUL [2] => VERDE [3] => AMARILLO )
Este ejemplo crea una matriz con base uno.
Example #4 Índice con base 1
<?php
$primercuarto = array(1 => 'Enero', 'Febrero', 'Marzo');
print_r($primercuarto);
?>
El resultado del ejemplo seria:
Array ( [1] => 'Enero' [2] => 'Febrero' [3] => 'Marzo' )
Example #5 Llenado de una matriz
<?php
// llenar una matriz con todos los ítems de un directorio
$gestor = opendir('.');
while (false !== ($archivo = readdir($gestor))) {
$archivos[] = $archivo;
}
closedir($gestor);
?>
Las matrices son ordenadas. Puede también cambiar el orden usando varias funciones de ordenamiento. Vea la sección sobre funciones de matrices para más información. Puede contar el número de items en una matriz usando la función count().
Example #6 Ordenamiento de una matriz
<?php
sort($archivos);
print_r($archivos);
?>
Dado que el valor de una matriz puede ser cualquier cosa, también puede ser otra matriz. De esta forma es posible crear matrices recursivas y multi-dimensionales.
Example #7 Matrices recursivas y multi-dimensionales
<?php
$frutas = array ( "frutas" => array ( "a" => "naranja",
"b" => "banano",
"c" => "manzana"
),
"numeros" => array ( 1,
2,
3,
4,
5,
6
),
"hoyos" => array ( "primero",
5 => "segundo",
"tercero"
)
);
// Algunos ejemplos que hacen referencia a los valores de la matriz anterior
echo $frutas["hoyos"][5]; // imprime "segundo"
echo $frutas["frutas"]["a"]; // imprime "naranja"
unset($frutas["hoyos"][0]); // elimina "primero"
// Crear una nueva matriz multi-dimensional
$jugos["manzana"]["verde"] = "bien";
?>
Debe advertir que la asignación de matrices siempre involucra la copia de valores. También quiere decir que el apuntador interno de matriz usado por current() y otras funciones similares es reestablecido. Necesita usar el operador de referencia para copiar una matriz por referencia.
<?php
$matriz1 = array(2, 3);
$matriz2 = $matriz1;
$matriz2[] = 4; // $matriz2 cambia,
// $matriz1 sigue siendo array(2, 3)
$matriz3 = &$matriz1;
$matriz3[] = 4; // ahora $matriz1 y $matriz3 son iguales
?>
Matrices
29-Apr-2008 10:14
18-Mar-2008 10:52
Sorting double dimensional arrays by a specified key bothe for Strings and for integers:
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 Field
function 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 helps
09-Jan-2008 05: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 that returns an array of values on success or NULL if nothing found.
$values = search(...);
Now you want to merge the array with another array. What do we do if $values is NULL? No problem:
$combined = array_merge((array)$values, $other);
Voila.
19-Dec-2007 01:25
z on 22-Apr-2005 12:10 wrote:
-----------------------------------------------
Here's a simple function to insert a value into some position in an array
<?php
function 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
<?php
function 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"));
print_r($b);
?>
10-Oct-2007 11: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 & security features.
//$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, Andrei Zmievski for wonderful PHP!';
?>
06-Sep-2007 08:36
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.
30-Aug-2007 10:56
<?php
//EXAMPLE of Multi-Dimentional Array where as an array's keys are an array itself.
//It's 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 to Jim 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.
?>
21-Aug-2007 11:59
Hey..
here is a function which helps to avoid using empty/isset
checkings for arrays.
(it's acts simillar to 'default' modifier in Smarty)
Using this function you will avoid 'Undefined index' or
'Undefined offset' error.
<?php
$_POST['id']['other'] = 'val1';
/*
key exist (same as $_POST['id'][other])
*/
echo getRequestParam('id[other]', 'default value');
/*
key doesn't 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;
else
return $ret;
}
/**
@access private
*/
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!
14-Jul-2007 05:34
Another note on unquoted array indices. Because it is first interpreted as a constant, it must obey the naming convention of constants. i.e. a letter or underscore 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]";
11-Jul-2007 02:41
<b>Mark Gukov</b> wrote below:
Regarding the fact that there's no need to quote arrays keys when enclosed in double 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."
-----------------------------------------------------------------
However, the following runs fine;
$r['a']['b'] = 'banana';
echo "{$r[a][b]} is tasty.";
Just box it!
24-May-2007 02:37
It's 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 of
unset and reindex: 0.22837495803833
splice: 0.22392416000366
20-Mar-2007 11:14
This Indonesian number speller function is twice
faster(*) than the one provided in class Terbilang by
anghuda(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 numbers
16-Mar-2007 10:44
On 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 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.
17-Jan-2007 02:55
About the automatic conversion of bare strings...
My opinion is that it never should have been implemented. Isn't it easier to NOT implement this "handy" feature in the first place? It is such a convenient way for "smart" programmers to write unsafe, not-futureproof code. Please remove this feature from future versions of PHP, please. (Hey, if you could change the OOP mechanisms between PHP 4 and PHP 5, why can't you make this change, right?)
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.
27-Sep-2006 11:18
Regarding the fact that there's no need to quote arrays keys when enclosed in double 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."
21-Sep-2006 05:30
Regarding the message of phoenixbytes:
The line foreach($bad as $baddies); will just yield in $baddies the last value of the array $bad.
I think that wasn't your intention, in that case there are faster and better ways than foreach.
I think what you wanted to do is:
<?php
foreach($bad as $baddies) // make a collection
{
if (preg_match("/$baddies/i", $mailto)) // find a match
{
$addrmail = "false";
}
else
{
$addrmail = "true";
}
} // foreach end
?>
26-Jul-2006 01:28
in response to ch dot martin at gmail dot com
If you are using the following code:
<?php
$r = array('05' => "abc", '35' => "def");
foreach ($r as $key=>$value)
var_dump($key);
?>
and you need the array key '35' to be a string (for looping maybe), you can make sure the key is a string by appending a 0 on the front.
'035' instead of '35'
09-Jun-2006 08:40
Extremely 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 (presumably because it leads with a zero). As far as I can see, there is absolutely no way of making string(2) "35" an array key.
25-May-2006 03:52
this 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','');
}
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","se\\1",$str);
return $str;
}
}
?>
09-May-2006 10:46
phoenixbytes: The regex you have posted for matching email addresses is incorrect. Among other things, it does not allow '+' before the '@' (which is perfectly valid and can be quite useful to separate extensions of a single address). RFC 822 [1] defines the grammar for valid email addresses, and (the extemely long) regex implementing can be found at [2]. Even the "Add Note" page here at php.net says:
[quote]
And if you're posting an example of validating email addresses, please don't bother. Your example is almost certainly wrong for some small subset of cases. See this information from O'Reilly Mastering Regular Expressions book for the gory details.
[/quote]
A note to others: please do your homework before writing another email-matching regex.
[1] http://www.ietf.org/rfc/rfc0822.txt?number=822
[2] http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html.
17-Apr-2006 02:10
i use the array() function for deciding upon an email address's validity, i have a 'wap stalker' of my site that loves to exploit every hole i leave, so i used the 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 sure it's an actual email address before going any further.
$mailto = "mail.domain.org"; // the input to be tested
if (preg_match("/^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,6}$/i", $mailto)) // see if it's really an email address
{
$bad = array('mytrashmail.com', 'mymail.ro', 'acasa.ro', 'gala.net', 'phoenixbytes'); // pick out the victims
foreach($bad as $baddies); // make a collection
if (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.
01-Apr-2006 10:54
Passing variables into the array constructor:
Just a NOOB pointer, I couldn't find other examples for this. If you want to pass the value of an existing variable into the array() constructor, you can quote it or not, both methods are valid.
<?
$foo_value = 'foo string';
$bar_value = 'bar string';
$myArray = array(
'foo_key' => $foo_value, // not quoted
'bar_key' => "$bar_value"); // quoted
foreach ($myArray as $k => $v) {
echo "\$myArray[$k] => $v.<br />\n";
}
?>
Both of these will work as expected, but the unqoted $foo_value method above is marginally faster because adding quotes adds an additional string de-reference.
13-Dec-2005 06:41
if you need to check a multidimensonal array for values it's handy to store it like
$ar['key1'][0]
$ar['key2'][0]
$ar['key3'][0]
$ar['key1'][1]
$ar['key2'][1]
$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 element
inside the array:
if(in_array($new_value,$channel['nr'])) print 'do something.';
Hope this helps someone.
30-Sep-2005 11:55
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 