Reset PHP Array Index

PhpArrays

Php Problem Overview


I have a PHP array that looks like this:

[3] => Hello
[7] => Moo
[45] => America

What PHP function makes this?

[0] => Hello
[1] => Moo
[2] => America

Php Solutions


Solution 1 - Php

The array_values() function [docs] does that:

$a = array(
    3 => "Hello",
    7 => "Moo",
    45 => "America"
);
$b = array_values($a);
print_r($b);

Array
(
    [0] => Hello
    [1] => Moo
    [2] => America
)

Solution 2 - Php

If you want to reset the key count of the array for some reason;

$array1 = [
  [3]  => 'Hello',
  [7]  => 'Moo',
  [45] => 'America'
];
$array1 = array_merge($array1);
print_r($array1);

Output:

Array(
  [0] => 'Hello',
  [1] => 'Moo',
  [2] => 'America'
)

Solution 3 - Php

Use array_keys() function get keys of an array and array_values() function to get values of an array.

You want to get values of an array:

$array = array( 3 => "Hello", 7 => "Moo", 45 => "America" );

$arrayValues = array_values($array);// returns all values with indexes
echo '<pre>';
print_r($arrayValues);
echo '</pre>';

Output:

Array
(
    [0] => Hello
    [1] => Moo
    [2] => America
)

You want to get keys of an array:

$arrayKeys = array_keys($array);// returns all keys with indexes
    echo '<pre>';
    print_r($arrayKeys);
    echo '</pre>';

Output:

Array
(
    [0] => 3
    [1] => 7
    [2] => 45
)

Solution 4 - Php

you can use for more efficient way :

$a = [
    3 => "Hello",
    7 => "Moo",
    45 => "America"
];

$a = [...$a];

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWalter JohnsonView Question on Stackoverflow
Solution 1 - PhpJeremyView Answer on Stackoverflow
Solution 2 - PhpAllan MwesigwaView Answer on Stackoverflow
Solution 3 - PhpGufran HasanView Answer on Stackoverflow
Solution 4 - PhpYohann Daniel CarterView Answer on Stackoverflow