0

I need to delete from a multi dimensional array.

My array looks as follows

Array(
   0 => Array(
      0 => "My Album",
      1 => "Testphoto2011-222231.jpg"
   ),
   1 => Array(
      0 => "Test Album",
      1 => "12345.jpg"
   )
);

What I want to do is search the value "My Album" and then delete the entire array from the array.

So for example the values "My Album" & "Testphoto2011-222231.jpg" belong to array[0]. When found I want to delete array[0].

Can anyone help me on this?

0

2 Answers 2

1
<?php
$ar = Array(
   Array(
      "My Album",
      "Testphoto2011-222231.jpg"
   ),
   Array(
      "Test Album",
      "12345.jpg"
   )
);

// Not using foreach, or ascending counting, because
// element removal will screw that up.
for ($i = count($ar) - 1; $i >= 0; $i--) {
   if ($ar[$i][0] == "My Album")
      unset($ar[$i]);
}

$ar = array_values($ar); // re-index

var_export($ar);

/* Output:
array (
  0 => 
  array (
    0 => 'Test Album',
    1 => '12345.jpg',
  ),
)
*/
?>

Live demo.

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

2 Comments

Brilliant thanks, i just have one question, My array is in a session, I used this code for ($i = count($_SESSION['albums']) - 1; $i >= 0; $i--) { if ($_SESSION['albums'][$i][0] == $album) unset($_SESSION['albums'][$i]); } $_SESSION['albums'] = array_values($_SESSION['albums']); // re-index var_export($_SESSION['albums']); is this right? At the moment its not updating the session array
@Wayne: Please use backticks to format code. And yes, that looks right.
0

unset($array[0]) will remove that entry from the array.

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.