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.
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...