Is there an easy way to remove an element from a PHP array, such that foreach ($array)
does not include that element anymore?
I thought that nullifying it would do it, but apparently not.
Is there an easy way to remove an element from a PHP array, such that foreach ($array)
does not include that element anymore?
I thought that nullifying it would do it, but apparently not.
If you have a numerically indexed array in which all values are unique (or are not unique but you want to delete all instances of a particular value), you can simply use array_diff()
to remove a matching element, like this:
$my_array = array_diff($my_array, array('Remover_valor'));
For example:
my_array = array('Andy', 'Bertha', 'Charles', 'Diana');
echo sizeof($my_array) . "\n";
$my_array = array_diff($my_array, array('Charles'));
echo sizeof($my_array);
This shows the following:
4
3
In this example, the element with the value 'Charles' is deleted as it can be verified by the calls sizeof()
that report a size of 4 for the initial matrix and 3 after the deletion.
A. If you want to eliminate all occurrences of the value within the array
You can combine the following PHP functions:
array_keys()
and unset()
In the example I implemented the function remover()
:
See DEMO for solutions A and B
<?php
//Caso A. Inicializando valores de ejemplo para probar la función
$arr= array(0 => 'azul', 1 => 'rojo', 2 => 'verde', 3 => 'rojo');
$arr_norojo=remover("rojo",$arr);
print_r($arr_norojo);
$arr_noazul=remover("azul",$arr);
print_r($arr_noazul);
/*
* Nuestra función usando array_keys() y unset()
* Devuelve un $arr sin el $valor pasado en parámetro
*/
function remover ($valor,$arr)
{
foreach (array_keys($arr, $valor) as $key)
{
unset($arr[$key]);
}
echo "Removiendo: ".$valor."\n\n";
return $arr;
}
Result:
Removiendo: rojo
Array
(
[0] => azul
[2] => verde
)
Removiendo: azul
Array
(
[1] => rojo
[2] => verde
[3] => rojo
)
B. If you want to delete only one occurrence:
You can combine unset()
quoted above, with array_search()
.
Example:
<?php
//Caso B. Inicializando valores de ejemplo para probar la función
$arr= array(0 => 'azul', 1 => 'rojo', 2 => 'verde', 3 => 'rojo');
$arr_norojo=remover_simple("rojo",$arr);
print_r($arr_norojo);
$arr_noazul=remover_simple("azul",$arr);
print_r($arr_noazul);
/*
* Nuestra función simple usando array_search() y unset()
* Devuelve un $arr sin la primera ocurrencia del $valor pasado en parámetro
*/
function remover_simple ($valor,$arr)
{
if (($key = array_search($valor, $arr)) !== false)
{
unset($arr[$key]);
}
echo "Removiendo sólo una vez: ".$valor."\n\n";
return $arr;
}
Result:
Removiendo sólo una vez: rojo
Array
(
[0] => azul
[2] => verde
[3] => rojo
)
Removiendo sólo una vez: azul
Array
(
[1] => rojo
[2] => verde
[3] => rojo
)
A simple way is using the "unset" function, I suppose you are working with "JSON" format since it is very used nowadays:
The syntax:
unset($nombre_del_array['clave_del_elemento']);