Eric
Eric

Reputation: 97555

How can I search for and delete an array element in PHP?

I have a PHP array that looks like this:

Array
(
 [0] => Array
 (
  [start] => DateTime Object
  (
  )

  [end] => DateTime Object
  (
  )

  [comment] => A comment.
 )

 [1] => Array
 (
  [start] => DateTime Object
  (
  )

  [end] => DateTime Object
  (
  )

  [comment] => Another comment.
 )
)

I would like to create a function that deletes an element (start,end,comment) from the array that matches the functions input, and returns false if it doesn't exist. Is there already a PHP function that does this?

Upvotes: 1

Views: 4749

Answers (2)

chaos
chaos

Reputation: 124257

Not exactly. You could do:

function array_remove(&$array, $search, $strict = false) { 
    $keys = array_keys($array, $search, $strict);
    if(!$keys)
        return false;
    foreach($keys as $key)
        unset($array[$key]);
    return count($keys);
}

Unlike using array_search(), this will work if there are multiple matching entries.

Upvotes: 2

soulmerge
soulmerge

Reputation: 75704

Guess you mean array_search():

while (($pos = array_search($input, $multiArray)) !== false) {
    unset($multiArray[$pos]);
}

Upvotes: 6

Related Questions