1

I have a array like below

$arr=array(

    array(

        'id'=> 342,
        'name' =>'srikanth',
        'age' => 32
    ),
    array(

        'id'=> 409,
        'name' =>'Ashok',
        'age' => 24
    ),
    array(

        'id'=> 314,
        'name' =>'Chakri',
        'age' => 25
    ),
    array(

        'id'=> 208,
        'name' =>'saikiran',
        'age' => 27
    )

);

I have to look for a specific id from the array for example id=409 which i am doing like below

$key=array_search("409",array_column($arr,"id"));

and copying the array to a temp variable like below and unsetting it:

$tmp=$arr[$key];


unset($arr[$key]);

Now what i want is to insert the temp array at my desired index in $arr.

I used below function to insert into my desired index but failed to get desired result.

function insertAt($array = [], $item = [], $position = 0) {
    $previous_items = array_slice($array, 0, $position, true);
    $next_items     = array_slice($array, $position, NULL, true);
    return $previous_items + $item + $next_items;
}


$arr=insertAt($arr,$tmp,0);

I want the temp array at 0 index (Not always at 0 index i know about array_unshift :) ) and my result array should look like this.

$arr=array(

    array(

        'id'=> 409,
        'name' =>'Ashok',
        'age' => 24
    ),
    array(

        'id'=> 342,
        'name' =>'srikanth',
        'age' => 32
    ),
    array(

        'id'=> 314,
        'name' =>'Chakri',
        'age' => 25
    ),
    array(

        'id'=> 208,
        'name' =>'saikiran',
        'age' => 27
    )

);
1
  • Use array_splice(). It removes zero or more elements and inserts zero or more elements instead of the removed ones.
    – axiac
    Commented Sep 20, 2017 at 6:18

1 Answer 1

3

array_splice() does the job for you:

// Find current position
$key = array_search(409, array_column($arr, 'id'));

// Get the element
$tmp = $arr[$key];

// Remove it from array
unset($arr[$key]);

// Insert it at a new position
$position = 0;
$arr = array_splice($arr, $position, 0, array($tmp));
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.