Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I've looked at all the questions about unsetting elements and I'm not making any of those mistakes, but the element is still there after I've unset it.

Update: I've incorporated RichardBernards suggestion below but this is still happening:

    foreach($oldObject AS $key1=>$val1)
    {
        if (!empty($val1)) 
        {
            $newObject->$key1 = $val1;
            if (is_array($oldObject->$key1)) 
            {
                foreach ($oldObject->$key1 as $key2 => $val2) 
                {
                    if (empty($val2)) 
                    {
                        print('Found to be empty: unsetting newObject->' . $key1 . '[' . $key2 . ']');
                        unset($newObject->$key1[$key2]);
                        if (array_key_exists($key2, $newObject->$key1)) 
                        {
                            print('The key ' . $key2 . ' still exists. What is going on?');
                        }
                    } 
                }
            }
        }
    }

In this code, the text "The key still exists. What is going on?" is being printed every time.

I have to unset empty elements because I'm making a SOAP call with the object, and SOAP rejects the object if there are any empty strings in it. But why does $newObject->$var[$key] still exist after I've explicitly unset it?

Is it because I'm trying to unset an element of an array inside an object?

Any help would be greatly appreciated.

share|improve this question

1 Answer 1

This is because you are unsetting the variable in the foreach over the array... This is not possible. Easiest way to solve this, is to copy the array and foreach over the first array, delete the key in the second array... Than use the second array further on in your code.

The long way around is by using functions like array_walk() or storing the keys you want to unset in different array and unset them after the foreach...

share|improve this answer
    
Thanks for your help. Since I was copying data from an old object anyway, I tried to iterate over the array in the old object, but I still seem to be getting the same result. –  TheBarnacle Nov 20 '14 at 11:10
    
Is the array being passed as a reference rather than copied? I've never quite figured out how referencing works in PHP. In Java it was easy. –  TheBarnacle Nov 20 '14 at 11:12

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.