1

I have an array of objects:

$obj = array();

// add the new items
$row = new stdClass();
$row->first = $first;
$row->last = $last;
$row->phone = $phone;

$obj[] = $row;

Now, if I only have the value of $last, is there a way to delete the entire $row object without specifying each key/value? (If it helps to understand, if it was a mysql statement it would be something like "DELETE * FROM $obj WHERE $row->last = 'Thomas' ")

thx

2
  • do you mean delete $row from $obj??? Commented Feb 26, 2011 at 0:36
  • i just threw that in...if it doesn't help clarify then ignore it Commented Feb 26, 2011 at 0:42

3 Answers 3

2

Is unset($row); what you want? But there is no need to do that if you are just doing it to save memory...

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

2 Comments

unset() does not immediately free memory. Memory, in PHP, gets freed when the garbage collector deems appropriate.
I think that this will not unset the array element, merely the original object. Although physically they may, for a while, be the same object in memory (hurray for copy-on-write) at this point they are semantically separate.
1

You need to know the key. However, if you iterate through the array you can find it.

/* Your original code: */
$obj = array();

// add the new items
$row = new stdClass();
$row->first = $first;
$row->last = $last;
$row->phone = $phone;

$obj[] = $row;

/* My addition: */
$theOneToDelete = $last;
foreach ($obj as $key => $row) {
   if ($row->last == $theOneToDelete) {
      unset($obj[$key]);
      break;
   }
}

There may be a terser approach with some of the array_* functions, but this lays it out.

Comments

1
foreach ($obj as $key => $value) {
  if($obj[$key]->last == $last){
    unset($obj[$key]);
  }
}

Oops, I forgot to format my response as code. I'm new here! =P

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.