php remove object from array of objects
Asked Answered
E

3

5

I'm trying to remove an object from an array of objects by its' index. Here's what I've got so far, but i'm stumped.

$index = 2;

$objectarray = array(
0=>array('label'=>'foo', 'value'=>'n23'),
1=>array('label'=>'bar', 'value'=>'2n13'),
2=>array('label'=>'foobar', 'value'=>'n2314'),
3=>array('label'=>'barfoo', 'value'=>'03n23')
);

//I've tried the following but it removes the entire array.
foreach ($objectarray as $key => $object) {
 if ($key == $index) {
   array_splice($object, $key, 1);
   //unset($object[$key]); also removes entire array.
 }
}

Any help would be appreciated.

Updated Solution

 array_splice($objectarray, $index, 1); //array_splice accepts 3 parameters 
    //(array, start, length) removes the given array and then normalizes the index
    //OR 
    unset($objectarray[$index]); //removes the array at given index
    $reindex = array_values($objectarray); //normalize index
    $objectarray = $reindex; //update variable 
Eleusis answered 4/2, 2014 at 17:51 Comment(2)
What are you trying to remove exactly?Psychologism
2=>array('label'=>'foobar', 'value'=>'n2314'Eleusis
E
13
    array_splice($objectarray, $index, 1); 
    //array_splice accepts 3 parameters (array, start, length) and removes the given 
    //array and then normalizes the index
    //OR 
    unset($objectarray[$index]); //removes the array at given index
    $reindex = array_values($objectarray); //normalize index
    $objectarray = $reindex; //update variable
Eleusis answered 4/2, 2014 at 21:51 Comment(0)
M
2

You have to use the function unset on your array.

So its like that:

<?php

$index = 2;

$objectarray = array(
    0 => array('label' => 'foo', 'value' => 'n23'),
    1 => array('label' => 'bar', 'value' => '2n13'),
    2 => array('label' => 'foobar', 'value' => 'n2314'),
    3 => array('label' => 'barfoo', 'value' => '03n23')
);
var_dump($objectarray);
foreach ($objectarray as $key => $object) {
    if ($key == $index) {
        unset($objectarray[$index]);
    }
}

var_dump($objectarray);
?>

Remember, your array will have odd indexes after that and you must (if you want) reindex it.

$foo2 = array_values($objectarray);
Murphy answered 4/2, 2014 at 17:58 Comment(1)
"your array will have odd indexes...". You solved my problem. ThxPenthouse
P
2

in that case you won't need that foreach just unset directly

unset($objectarray[$index]);
Psychologism answered 4/2, 2014 at 18:0 Comment(2)
@Eleusis it must be something else then... i've just tested this and it works perfectly. are you making any unsets afterwards or before?Psychologism
You were correct, I had a malformed if statement previous to this code that was causing $objectarray = '';. Your solution works, but I think array_splice is going to be more efficient for my use case. I've updated my question.Eleusis

© 2022 - 2024 — McMap. All rights reserved.