Question

I am trying to unset something in an object.

foreach($curdel as $key => $value) {
if ($value == $deletedinfo[0]) {
    print_r($key);
    print_r($curdel);
    unset($curdel[$key]);
}
}

As expected, $key returns the correct value (0) and $curdel returns the entire array. But trying to unset $curdel[$key] breaks everything. even trying to print_r($curdel[$key]) breaks everything, what am I missing?

My object looks like this:

stdClass Object ( [0] => IFSO14-03-21-14.csv [2] => EB_Bunny.jpg [3] => EB_White_Bear.jpg )
Was it helpful?

Solution

Instead of:

unset($curdel[$key]);

Try:

unset($curdel->$key);

Arrays are accessed/modified via the [] but objects and class properties are accessed via the ->

OTHER TIPS

Possible solution to that problem is to add reference to $value variable:

foreach($curdel as $key => &$value) { //Note & sign
   if ($value == $deletedinfo[0]) {
       print_r($key);
       print_r($curdel);
       unset($curdel[$key]);
   }
}

&$value means a reference to an actual array element

Answer based also on this (similar) example: Unset an array element inside a foreach loop

UPDATE

Based in your input (STDClass instead of array): just cast $curdel to array first:

$curdel = (array) $curdel ;

Numeric indices in objects are kinda invalid and can be accessed only via special syntax like:

$object->{'0'} ;

which is a really bad practice.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top