0

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?

0

4 Answers 4

2
$array = [5, 2, 9];

print_r($array);

outputs:

Array
(
    [0] => 5
    [1] => 2
    [2] => 9
)
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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 );

2 Comments

Sorry, was a typo in my question. It should be 0 1 2
@BrentThierens This will work for your case, since you already have two arrays. So, just combine two arrays.
0

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

1 Comment

Exactly, arrays already have indexes like 0,1,2. For custom case we have insert indexes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.