0

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 )
halfer
  • 19,824
  • 17
  • 99
  • 186
jrabramson
  • 105
  • 1
  • 8
  • What do you mean - breaks everything? Any real error messages? – sybear Mar 24 '14 at 20:40
  • Breaks everything? what is the error? – Kamehameha Mar 24 '14 at 20:40
  • No errors, nothing renders after I try it. – jrabramson Mar 24 '14 at 20:43
  • print_r $curdel returns: `stdClass Object ( [0] => IFSO14-03-21-14.csv [2] => EB_Bunny.jpg [3] => EB_White_Bear.jpg )` – jrabramson Mar 24 '14 at 20:46
  • So you know for future questions, this data structure is an object with numeric properties, not an "object array". I suspect that if you use that phrase, people will assume you mean a class that implements the [`Iterator`](http://php.net/manual/en/class.iterator.php) interface. – halfer Mar 24 '14 at 21:40

2 Answers2

4

Instead of:

unset($curdel[$key]);

Try:

unset($curdel->$key);

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

Aziz Saleh
  • 2,687
  • 1
  • 17
  • 27
2

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.

Community
  • 1
  • 1
sybear
  • 7,837
  • 1
  • 22
  • 38
  • The foreach and if didn't seem to be the issues as the two print_r are going off. – jrabramson Mar 24 '14 at 20:44
  • Seriously, just explain what input you have and what final result you need to get. Post more code that could possibly cause the problem and we will help you. `Breaks everything` is the same as `ERROR_NOT_FOUND` – sybear Mar 24 '14 at 20:51
  • I think this is a good answer based on the information available at the time: `object != object array`! – halfer Mar 24 '14 at 21:38