Weblog
How to remove an element from an array
Soo, I’m learning more and more php these days and today I stumbled onto a problem, which I couldn’t solve myself.
How do you remove an element from an array in php?
After a quick google search I found this:
foreach($array as $key => $value) {
if($value == "" || $value == " " || is_null($value)) {
unset($array[$key]);
}
}
/*
and if you want to create a new array with the keys reordered accordingly
*/
$new_array = array_values($array);
Tnx to Scriptygoddess
This works okay, but I’m wondering if this is the best/quickest way to remove an element from an array?
And isn’t there a built-in function in php that does the same thing?
The Fine print™: By submitting a comment here you grant this site a perpetual license to reproduce your words and name/web site in attribution.
Your email is never published nor shared. Required fields are marked *
Denis Mazourick
Why not just use array_splice?
The script will look like
///////////////////////
//Cleanup array
for ($i = count($array) – 1; $i >= 0; $i–)
{
if ($array[$i] == “” || $array[$i] == ” ” || is_null($array[$i]))
array_splice($array, $i, 1);
}
//////////////////////////
Should be faster than copying all values from one array to another especially on large arrays.
Posted on: 19/6/2008 at 17:12 - #
Catalin
for ($i = count($array) – 1; $i >= 0; $i–-)
Should be
$no = count($array);
for ($i = $no – 1; $i >= 0; $i–-)
tnx
Posted on: 16/11/2009 at 0:12 - #
Hasan Cosgun
$n = count($arr) -1;
for ($i = $n; $i >=0; $i–){
if (!trim($arr[$i]) // this solves: if 2,3 spaces in value?
array_splice($arr,$i,1);
}
// DONE
// remove _’s from email
Posted on: 12/1/2010 at 17:51 - #