1

I want to remove an element from a PHP array (and shrink the array size). Just looking at the PHP docs, it seems this can be done using array_slice() and array_merge()

so I am guessing (off the top of my head) that some combination of array_merge() and array_slice will work. However, array_slice() requires an index (not a key), so I'm not sure how to quickly cobble these functions together for a solution.

Has anyone implemented such a function before?. I'm sure it must be only a few lines long, but I cant somehow get my head around it (its been one of those days) ...

Actually, I just came up with this cheesy hack when writing up this question....

function remove_from_array(array $in, value) {
   return array_diff($in, (array)$value);
}

too ugly? or will it work (without any shocking side effects)?

0

6 Answers 6

6

This functionality already exists; take a look at unset.

http://php.net/manual/en/function.unset.php


$a = array('foo' => 'bar', 'bar' => 'gork');
unset($a['bar']);
print_r($a);

output will be:

array(
[foo] => bar
)
Sign up to request clarification or add additional context in comments.

1 Comment

what if it's indexed by numbers?
1

There's the array_filter function that uses a callback function to select only wanted values from the array.

Comments

1

you want an unset by value. loop through the array and unset the key by value.

Comments

0
unset($my_array['element']);

Won't work?

4 Comments

This is really a comment, not an answer to the question. Please use "add comment" to leave feedback for the author.
@Jack Why do you think it is a comment?
Because it looks like one? Surely you could have spent a few more seconds to make it a proper answer.
AFAIK it answers the question fully and correctly, no need to add extra garbage to the answer.
0

This code can be replaced by single array_filter($arr) call

Comments

0
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);

1 Comment

FYI - Your if statement can be improved a bit if you would use php's empty() functionality.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.