Made this function to delete elements in an array;
<?php
function array_del_elm($input_array, $del_indexes) {
if (is_array($del_indexes)) {
$indexes = $del_indexes;
} elseif(is_string($del_indexes)) {
$indexes = explode($del_indexes, " ");
} elseif(is_numeric($del_indexes)) {
$indexes[0] = (integer)$del_indexes;
} else return;
$del_indexes = null;
$cur_index = 0;
if (sort($indexes)) for($i=0; $i<count($input_array); $i++) {
if ($i == $indexes[$cur_index]) {
$cur_index++;
if ($cur_index == count($indexes)) return $output_array;
continue;
}
$output_array[] = $input_array[$i];
}
return $output_array;
}
?>
but then i saw the methods of doing the same by Tyler Bannister & Paul, could see that theirs were faster, but had floors regarding deleting multiple elements thus support of several ways of giving parameters. I combined the two methods to this to this:
<?php
function array_del_elm($target_array, $del_indexes) {
if (is_array($del_indexes)) {
$indexes = $del_indexes;
} elseif(is_string($del_indexes)) {
$indexes = explode($del_indexes, " ");
} elseif(is_numeric($del_indexes)) {
$indexes[0] = (integer)$del_indexes;
} else return;
unset($del_indexes);
for($i=0; $i<count($indexes); $i++) {
unset($target_array[$indexes[$i]]);
}
return $target_array;
}
?>
Fast, compliant and functional ;)
Arrays
- Introducción
- Installing/Configuring
- Constantes predefinidas
- Sorting Arrays
- Array Functions
- array_change_key_case — Devuelve una matriz con todas las claves de las cadenas convertidas a mayúsculas o minúsculas
- array_chunk — Divide una matriz en segmentos
- array_combine — Crea una nueva matriz, usando una matriz para las claves y otra para sus valores
- array_count_values — Cuenta todos los valores de una matriz
- array_diff_assoc — Comprueba las diferencias entre matrices teniendo en cuenta los índices
- array_diff_key — Calcula la diferencia de matrices usando las llaves para la comparación
- array_diff_uassoc — Computa la diferencia entre matrices con un chequeo adicional de índices, el cual es realizado por una llamada de retorno entregada por el usuario
- array_diff_ukey — Calcula la diferencia de matrices usando callback function on the keys for comparison
- array_diff — Comprueba las diferencias entre matrices
- array_fill_keys — Fill an array with values, specifying keys
- array_fill — Llena una matriz con valores
- array_filter — Filtra elementos de una matriz mediante una función "callback"
- array_flip — Intercambia los valores de una matriz con sus índices
- array_intersect_assoc — Calcula la intersección de matrices verificando que también coincidan los índices
- array_intersect_key — Calcula la intersección de matrices usando las llaves para la comparación
- array_intersect_uassoc — Calcula la intersección de matrices con chequeo de índices adicional por una función de usuario
- array_intersect_ukey — Calcula la intersecció de matrices usando una función de usuario para la comparación de los índices
- array_intersect — Calcula la intersección de matrices
- array_key_exists — Comprueba si el índice o clave dada existe en la matriz
- array_keys — Devuelve todas las claves de una matriz
- array_map — Aplica la llamada de retorno especificada a los elementos de las matrices dadas
- array_merge_recursive — Une dos o más matrices recursivamente
- array_merge — Combina dos o más matrices
- array_multisort — Ordena múltiples matrices, o matrices multi-dimensionales
- array_pad — Rellena una matriz con un valor hasta el tamaño especificado
- array_pop — Extrae el último elemento de la matriz
- array_product — Calcula el producto de valores en una matriz
- array_push — Inserta uno o más elementos al final de la matriz
- array_rand — Selecciona una o más entradas aleatorias de una matriz
- array_reduce — Reduce iterativamente una matriz a un solo valor usando una función llamada de retorno
- array_replace_recursive — Replaces elements from passed arrays into the first array recursively
- array_replace — Replaces elements from passed arrays into the first array
- array_reverse — Devuelve una matriz con los elementos en orden inverso
- array_search — Busca un valor determinado en una matriz y devuelve la clave correspondiente en caso de éxito
- array_shift — Extrae un elemento del comienzo de la matriz
- array_slice — Extrae una porción de la matriz
- array_splice — Suprime una porción de la matriz y la sustituye por otra cosa
- array_sum — Calcula la suma de los valores en una matriz
- array_udiff_assoc — Computa la diferencia entre matrices con un chequeo de índices adicional, comparando los datos con una llamada de retorno
- array_udiff_uassoc — Computa la diferencia entre matrices con un chequeo de índices adicional, comparando los datos y los índices con una llamada de retorno
- array_udiff — Computa la diferencia entre matrices, usando una llamada de retorno para la comparación de datos
- array_uintersect_assoc — Calcula la intersección de matrices con chequeo adicional de ídices, comparando los datos por una función del usuario
- array_uintersect_uassoc — Calcula la intersección de matrices con chequeo adicional de índices, compara los datos y los índices por una función del usuario
- array_uintersect — Calcula la interseccón de matrices, compara los datos con una función del usuario
- array_unique — Remueve valores duplicados de una matriz
- array_unshift — Introduce uno o más elementos al principio de la matriz
- array_values — Devuelve todos los valores de una matriz
- array_walk_recursive — Aplicar una función de usuario recursivamente a cada miembro de una matriz
- array_walk — Aplica una función del usuario a cada elemento de una matriz.
- array — Crear una matriz
- arsort — Ordena una matriz en orden inverso y mantiene la asociación de índices
- asort — Ordena una matriz y mantiene la asociación de índices
- compact — Crea una matriz que contiene variables y sus valores
- count — Cuenta los elementos de una matriz o propiedades de un objeto
- current — Devuelve el elemento actual de una matriz
- each — Devuelve el siguiente par clave/valor de una matriz y avanza el apuntador
- end — Mueve el puntero interno de una tabla al último elemento
- extract — Importa variables a la tabla de símbolos desde una matriz
- in_array — Revisa si un valor existe en una matriz
- key — Obtiene una clave de una matriz asociativa
- krsort — Ordena una matriz por clave en orden inverso
- ksort — Ordena una matriz por clave
- list — Asigna variables como si fueran una matriz
- natcasesort — Ordena una matriz usando un algoritmo de "orden natural" sin distinguir mayúsculas de minúsculas
- natsort — Ordena una matriz usando un algoritmo de "orden natural"
- next — Avanza el puntero interno de una matriz
- pos — Alias de current
- prev — Rebobina el puntero interno de una matriz
- range — Crea una matriz que contiene un rango de elementos
- reset — Fija el puntero interno de una matriz a su primer elemento
- rsort — Ordena una matriz en orden inverso
- shuffle — Mezcla una matriz
- sizeof — Alias of count
- sort — Ordena una matriz
- uasort — Ordena una matriz mediante una función de comparación definida por el usuario y mantiene la asociación de índices
- uksort — Ordena una matriz por claves mediante una función definida por el usuario
- usort — Ordena una matriz por sus valores usando una función de comparación definida por el usuario
Arrays
sunear at gmail dot com
04-Aug-2009 05:45
04-Aug-2009 05:45
Tyler Bannister
11-Jun-2009 01:59
11-Jun-2009 01:59
To delete an individual array element use the unset function
For example:
<?PHP
$arr = array( "A", "B", "C" );
unset( $arr[1] );
// now $arr = array( "A", "C" );
?>
Unlink is for deleting files.
Paul
21-May-2009 09:05
21-May-2009 09:05
To delete an individual array element use the unlink function
For example:
<?PHP
$arr = array( "A", "B", "C" );
unlink( $arr[1] );
// now $arr = array( "A", "C" );
?>
thomasdecaux at ebuildy dot com
15-May-2009 08:14
15-May-2009 08:14
To browse a simple array:
<?php
foreach ($myArray AS $myItem)
{
}
?>
To browse an associative array:
<?php
foreach ($myArray AS $key=>$value)
{
}
?>
http://www.ebuildy.com
macnimble at gmail dot com
27-Mar-2009 02:59
27-Mar-2009 02:59
Converting a linear array (like a mysql record set) into a tree, or multi-dimensional array can be a real bugbear. Capitalizing on references in PHP, we can 'stack' an array in one pass, using one loop, like this:
<?php
# array_stack()
# Original idea from:
# http://www.ideashower.com/our_solutions/
# create-a-parent-child-array-structure-in-one-pass/
function array_stack (&$a, $p = '@parent', $c = '@children')
{
$l = $t = array();
foreach ($a AS $key => $val):
if (!$val[$p]) $t[$key] =& $l[$key];
else $l[$val[$p]][$c][$key] =& $l[$key];
$l[$key] = (array)$l[$key] + $val;
endforeach;
return $a = array('tree' => $t, 'leaf' => $l);
}
# Example:
$node = array();
$node[1] = array('@parent' => 0, 'title' => 'I am node 1.');
# ^-----------------------v Link @parent value to key.
$node[2] = array('@parent' => 1, 'title' => 'I am node 2.');
$node[3] = array('@parent' => 2, 'title' => 'I am node 3.');
$node[4] = array('@parent' => 1, 'title' => 'I am node 4.');
$node[5] = array('@parent' => 4, 'title' => 'I am node 5.');
array_stack($node);
$node['leaf'][1]['title'] = 'I am node one.';
$node['leaf'][2]['title'] = 'I am node two.';
$node['leaf'][3]['title'] = 'I am node three.';
$node['leaf'][4]['title'] = 'I am node four.';
$node['leaf'][5]['title'] = 'I am node five.';
echo '<pre>',print_r($node['tree'],TRUE),'</pre>';
?>
Note that there's no parameter checking on the array value, but this is only to keep the function size small. One could easily a quick check in there to make sure the $a parameter was in fact an array.
Hope you find it useful. Huge thanks to Nate Weiner of IdeaShower.com for providing the original function I built on.
andyd273 at gmail dot com
24-Feb-2009 09:12
24-Feb-2009 09:12
A small correction to Endel Dreyer's PHP array to javascript array function. I just changed it to show keys correctly:
function array2js($array,$show_keys)
{
$dimensoes = array();
$valores = array();
$total = count ($array)-1;
$i=0;
foreach($array as $key=>$value){
if (is_array($value)) {
$dimensoes[$i] = array2js($value,$show_keys);
if ($show_keys) $dimensoes[$i] = '"'.$key.'":'.$dimensoes[$i];
} else {
$dimensoes[$i] = '"'.addslashes($value).'"';
if ($show_keys) $dimensoes[$i] = '"'.$key.'":'.$dimensoes[$i];
}
if ($i==0) $dimensoes[$i] = '{'.$dimensoes[$i];
if ($i==$total) $dimensoes[$i].= '}';
$i++;
}
return implode(',',$dimensoes);
}
Endel Dreyer
20-Jan-2009 12:16
20-Jan-2009 12:16
Function to convert PHP arrays to JavaScript Array Object:
Useful in some cases.
<?php
function array2js($array,$show_keys=false)
{
$dimensoes = array();
$valores = array();
$total = count ($array)-1;
$i=0;
foreach ($array as $key => $value) {
if (is_array($value)) {
$dimensoes[$i] = array2js($value,$show_keys);
} else {
$dimensoes[$i] = '"'.addslashes($value).'"';
if ($show_keys) '"'.$key.'":'.$dimensoes[$i];
}
if ($i==0) $dimensoes[$i] = '['.$dimensoes[$i];
if ($i==$total) $dimensoes[$i].= ']';
$i++;
}
return implode(',',$dimensoes);
}
?>
Anonymous
26-Nov-2008 06:36
26-Nov-2008 06:36
@jorge at andrade dot cl
This variant is faster:
<?php
function array_avg($array,$precision=2){
if(!is_array($array))
return 'ERROR in function array_avg(): this is a not array';
foreach($array as $value)
if(!is_numeric($value))
return 'ERROR in function array_avg(): the array contains one or more non-numeric values';
$cuantos=count($array);
return round(array_sum($array)/$cuantos,$precision);
}
?>
jorge at andrade dot cl
12-Nov-2008 08:03
12-Nov-2008 08:03
To calculate the average of a array
<?php
function array_avg($array,$precision="2"){
$a=0;
if(is_array($array)){
foreach($array as $value):
if(!is_numeric($value)){
$a++;
}
endforeach;
if($a==0){
$cuantos=count($array);
return round(array_sum($array)/$cuantos,$precision);
}else{
return "ERROR in function array_avg(): the array contains one or more non-numeric values";
}
}else{
return "ERROR in function array_avg(): this is a not array";
}
}
?>
alan dot lake at lakeinfoworks dot com
22-Oct-2008 03:46
22-Oct-2008 03:46
To delete an array key (and its value) from an array:
<?php
function array_delete(&$ary,$key_to_be_deleted)
{
$new = array();
if(is_string($key_to_be_deleted)) {
if(!array_key_exists($key_to_be_deleted,$ary)) {
return;
}
foreach($ary as $key => $value) {
if($key != $key_to_be_deleted) {
$new[$key] = $value;
}
}
$ary = $new;
}
if(is_array($key_to_be_deleted)) {
foreach($key_to_be_deleted as $del) {
array_delete(&$ary,$del);
}
}
}
?>
webmaster at infoproducts dot x10hosting dot com
11-Oct-2008 02:13
11-Oct-2008 02:13
New value can also be added to the array as shown below.
$theVariable["google"] = "http//google.com";
or
$theVariable["1"] = "http//google.com";
Jack A
07-Oct-2008 03:14
07-Oct-2008 03:14
Note that arrays are not allowed in class constants and trying to do so will throw a fatal error.
contact at greyphoenix dot biz
01-Jul-2008 04:36
01-Jul-2008 04:36
<?php
//Creating a multidimensional array
$theVariable = array("Search Engines" =>
array (
0=> "http//google.com",
1=> "http//yahoo.com",
2=> "http//msn.com/"),
"Social Networking Sites" =>
array (
0 => "http//www.facebook.com",
1 => "http//www.myspace.com",
2 => "http//vkontakte.ru",)
);
echo "The first array value is " . $theVariable['Search Engines'][0];
?>
-- Output--
The first array value is http://google.com
applegrew at rediffmail dot com
28-May-2008 03:23
28-May-2008 03:23
For newbies like me.
Creating new arrays:-
//Creates a blank array.
$theVariable = array();
//Creates an array with elements.
$theVariable = array("A", "B", "C");
//Creating Associaive array.
$theVariable = array(1 => "http//google.com", 2=> "http://yahoo.com");
//Creating Associaive array with named keys
$theVariable = array("google" => "http//google.com", "yahoo"=> "http://yahoo.com");
Note:
New value can be added to the array as shown below.
$theVariable[] = "D";
$theVariable[] = "E";
