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 )
5
  • What do you mean - breaks everything? Any real error messages? Commented Mar 24, 2014 at 20:40
  • Breaks everything? what is the error? Commented Mar 24, 2014 at 20:40
  • No errors, nothing renders after I try it. Commented Mar 24, 2014 at 20:43
  • print_r $curdel returns: stdClass Object ( [0] => IFSO14-03-21-14.csv [2] => EB_Bunny.jpg [3] => EB_White_Bear.jpg ) Commented Mar 24, 2014 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 interface. Commented Mar 24, 2014 at 21:40

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

This guy, this guy knows whats up.
Note: unset($obj->prop) DELETEs prop from the object, such that __get() and __set() will be invoked on future $obj->prop access, even if the property is declared as public.
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.

3 Comments

The foreach and if didn't seem to be the issues as the two print_r are going off.
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
I think this is a good answer based on the information available at the time: object != object array!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.