0

I built this function in PHP so far called removeAllValuesMatching, but I cannot seem to get it working. I am passing in two parameters $arr and $value. Not sure why this is happening. Any help would be greatly appreciated. This is what I have so far:

<?php 
$arr = array(
   'a' => "one",
   'b' => "two",
   'c' => "three",
   'd' => "two",
   'e' => "four",
   'f' => "five",
   'g' => "three",
   'h' => "two"
);
function removeAllValuesMatching($arr, $value){
 foreach ($arr as $key => $value){
 if ($arr[$key] == $value){
 unset($arr[$key]);
 }
 }
 return $arr = array_values($arr);
 }

print_r(removeAllValuesMatching($arr, "two"));

?>
2
  • What isn't working? "I am passing in two parameters $arr and $value. Not sure why this is happening." - are you missing something between these two sentences? Commented May 30, 2012 at 18:04
  • When I pass in the parameter of ($arr, "two"), It prints out none of the elements of the array. It should print out to the screen one, three, four, five, three Commented May 30, 2012 at 18:04

3 Answers 3

3

You're overwriting $value here:

foreach ($arr as $key => $value){

Simply rename it:

foreach ($arr as $key => $val) {
    if ($val == $value) {

However, a better way to delete elements from an array is this:

function removeAllValuesMatching(array $arr, $value) {
    $keys = array_keys($arr, $value);
    foreach ($keys as $key) {
        unset($arr[$key]);
    }
    return $arr;
}
Sign up to request clarification or add additional context in comments.

Comments

0

This is my full version, with no variables collision and indenting : that's not an option, you should always indent correctly

<?php 
$arr = array(
    'a' => "one",
    'b' => "two",
    'c' => "three",
    'd' => "two",
    'e' => "four",
    'f' => "five",
    'g' => "three",
    'h' => "two"
);

function removeAllValuesMatching($arr, $arg){
    foreach ($arr as $key => $value){
        if ($arr[$key] == $arg){
            unset($arr[$key]);
        }
    }
    return $arr = array_values($arr);
}

print_r(removeAllValuesMatching($arr, "two"));

?>

Comments

0

Not a fix for your method, but array_diff will acheive the same result, while also allowing you to remove multiple values.

$arr = [
   'a' => "one",
   'b' => "two",
   'c' => "two",
   'd' => "three",
];  
$filtered = array_diff($arr, ['one', 'two']);
print_r($filtered); // Array([d] => three) 

1 Comment

And, of course, you could update the original array without an intermediary array: $arr = array_diff($arr, ['one', 'two']);

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.