Rubberduck1337106092
Rubberduck1337106092

Reputation: 1344

How to push into an array and not reset index PHP

I have and array and i need to push a value into the first index(0).

array:3 [▼
  4 => "test1"
  5 => "test2"
  6 => "test3"
]

I need the indexes to stay like this, so the array will become like below. Since the indexes are the IDS of the values.

array:3 [▼
  0 => "None selected"
  4 => "test1"
  5 => "test2"
  6 => "test3"
]

To populate array:

$accuGroups = UpselGroup::where('accu_group','1')->with('UpselProducts.products')->pluck('naam','id')->toArray();

What i tried:

$accuGroups = array_merge([0 => 'None selected'], $accuGroups);

outcome (not what i want):

array:4 [▼
  0 => "None selected"
  1 => "test1"
  2 => "test2"
  3 => "test3"
]

Any help is appreciated

thanks

Upvotes: 0

Views: 360

Answers (6)

Klaus Mikaelson
Klaus Mikaelson

Reputation: 572

You can try this

<?php
    $array = array('4' => 'test1','5' => 'test2', '6' => 'test3');
    $add = array('0'=>'None selected');
    $final =  $add + $array;
    echo "<pre>";print_r($final);die;
?>

Upvotes: 0

Piyush Kumar
Piyush Kumar

Reputation: 48

Keep another value which you have to merge as array and add it to first array and you will get result.

$a=['4' => "test1", '5' => "test2",'6' => "test3"];
$b=['0'=>'Not Selected'];
$c=$b+$a;

in $c you will get result as per your requirement.

Upvotes: 0

JYoThI
JYoThI

Reputation: 12085

array_merge() function, and the keys are integers, the function returns a new array with integer keys starting at 0 and increases by 1 for each value

so use like this :

$accuGroups[0]="None selected";

Upvotes: 2

ThataL
ThataL

Reputation: 165

$accuGroups[0]="Not Selected.";
$accuGroups[6]="Not Selected.";

The array will reset its index value with given Value;

Upvotes: 0

Bilal Ahmed
Bilal Ahmed

Reputation: 4076

you can try this

<?php
    $queue = array("test1", "test2","test3", "test4");
    array_unshift($queue, "None selected");
    echo "<pre>";
    print_r($queue);
    ?>

Upvotes: 0

Sapnesh Naik
Sapnesh Naik

Reputation: 11656

Try this

$none_selected = array(
        0 => 'None selected');

    $accuGroups = $none_selected + $accuGroups;

Upvotes: 0

Related Questions