Home > front end >  Insert at any position a php object into an array of objects
Insert at any position a php object into an array of objects

Time:08-10

I want to insert $my_object into an array of objects, for example between the fourth and fifth element of $my_array_of_objects.


$my_object = myObject ();

$my_array_of_objects = Array ( 
[1] => Object ()
[2] => Object ()
[3] => Object ()
[4] => Object ()
[5] => Object ()
)

// to something like this :
$my_array_of_objects = Array ( 
[1] => Object ()
[2] => Object ()
[3] => Object ()
[4] => Object ()
[5] => myObject () //the position i want to insert my object
[6] => Object ()
)

I try this but it dosen't work. array_splice($my_array_of_objects, 0, 4, $my_object);

I know how to add $my_object at the end of the array but not at any position. Any help would be greatly appreciated!

Thanks!

CodePudding user response:

Create a new array, by slicing and merging.

$array = [1,2,3,4,5,6];

$insertPosition = 4;
$newElement= 'ABC';
$newArray = array_merge(array_slice($array, 0, $insertPosition), [$newElement], array_slice($array, $insertPosition));

print_r($newArray);

gives you

(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => ABC
    [5] => 5
    [6] => 6
)

Alternative

Instead of using arrays, you could use a Double Linked List. Because it implements the Iterable interface, you can also foreach over it.

$list = new SplDoublyLinkedList();
$list->push(1);
$list->push(2);
$list->push(3);
$list->push(4);
$list->push(5);
$list->push(6);

$list->add(4, 'ABC');
print_r($list);

gives

SplDoublyLinkedList Object
(
    [flags:SplDoublyLinkedList:private] => 0
    [dllist:SplDoublyLinkedList:private] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
            [3] => 4
            [4] => ABC
            [5] => 5
            [6] => 6
        )

)

CodePudding user response:

Correct call with array_splice will be:

array_splice($my_array_of_objects, 4, 0, [$my_object]);

Which means:

  • starting at position 4 remove 0 elements in $my_array_of_objects.
  • replace these "deleted" elements with values from array which holds only one value - $my_object.

CodePudding user response:

Please check this

$my_object = myObject ();

$postion = 4;

$my_array_of_objects = Array ( 
[1] => Object ()
[2] => Object ()
[3] => Object ()
[4] => Object ()
[5] => Object ()
)


$new_objects_array = array();

for($i=0;$i<count($my_array_of_objects);$i  )
{
    if($i == $postion)
    {
        array_push($new_objects_array , $my_object);
    
    }
    else
    {
    
        array_push($new_objects_array , $my_array_of_objects[$i]);
    }
    

}

let me know if it's working

cheers !!

CodePudding user response:

Try

$my_array_of_objects[5] = $my_object

  • Related