Laravel / PHP为值添加键

I have an array like so:

[5, 2, 9] 

However, I need this array:

[0 => 5, 1 => 2, 2 => 9]

So I need the index as key. Is there a function to achieve this? Now I create an empty array manually and I use array_push through a foreach loop. It works, however this doesn't seem elegant.

Is there a better solution?

$array = [5, 2, 9];

print_r($array);

outputs:

Array
(
    [0] => 5
    [1] => 2
    [2] => 9
)

if you print array in loop you can see default key

$arr=[5, 2, 9];
foreach($arr as $key=>$val){
  echo 'Key='.$key.','.'val='.$val.'<br/>';
}

OUTPUT

Key=0,val=5
Key=1,val=2
Key=2,val=9

Also if you echo using key like

$arr=[5, 2, 9];

echo $arr[1];

output

2

Use array_combine,

At first, create an array of values,

  $values = array(5, 2, 9);

Now, create an array of keys,

  $keys = array(0, 1, 2);

After that, Combine two array to get result,

  $result = array_combine ( array $keys , array $values );

Your array already has the keys based off its position in the array

$test = [5, 2, 9];


print_r($test);

Array ( [0] => 5 [1] => 2 [3] => 9 ) 

echo $test[0]; = 5
echo $test[1]; = 2
echo $test[3]; = 9