0

I have array:

Array
(
    [5] => Array
        (
            [0] => 19
            [1] => 18
        )

    [6] => Array
        (
            [0] => 28
        )

)

And I'm trying to delete element by value using my function:

function removeElementWithValue($obj, $delete_value){

    if (!empty($obj->field)) {
         foreach($obj->field as $key =>$value){
            if (!empty($value)) {
                foreach($value as $k=>$v){
                    if($v == $delete_value){
                       $obj->field[$key][$k] = '';
                    }
                }
            }
         }
    }
    return urldecode(http_build_query($obj->field));
}

echo removeElementWithValue($request, '19');

After operation above I have: 5[0]=&5[1]=18&6[0]=28; // Right!!!

echo removeElementWithValue($request, '18');

After operation above I have: 5[0]=&5[1]=&6[0]=28; // Wrong ???

But my expected result after second operation is:

5[0]=19&5[1]=&6[0]=28;

Where is my mistake? Thanks!

2
  • 1
    your function is for StdClass Objects and you are passing array. why ? Commented Jun 10, 2015 at 9:17
  • That's apparently not possible, as once you have deleted the value you, you cannot regain it. The alternative is make a copy of your original array to some other variable. now, apply your operations on the new copied variable. Commented Jun 10, 2015 at 9:34

2 Answers 2

1

Use array_walk_recursive to find and change value

$arr = Array (
    5 => Array ( 0 => 19, 1 => 18 ),
    6 => Array ( 0 => 28));

$value = 18;

array_walk_recursive($arr, 
      function (&$item, $key, $v) { if ($item == $v) $item = ''; }, $value);

print_r($arr); 

result:

Array (
    5 => Array ( 0 => 19, 1 =>  ),
    6 => Array ( 0 => 28));
Sign up to request clarification or add additional context in comments.

Comments

0

A simpler function might be..

function removeElementWithValue($ar,$val){

    foreach($ar as $k=>$array){
        //update the original value with a new array
        $new_ar = array_diff_key($array,array_flip(array_keys($array,$val)));
        if($new_ar){
            $ar[$k]=$new_ar;
        }else{
            unset($ar[$k]);//or remove the empty value
        }
    }

    return $ar;
}

Comments

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.