Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reset PHP Array Index

Tags:

arrays

php

People also ask

How do you clear an array in PHP?

Use the unset() Function to Reset an Array in PHP We will use the unset() function to clear array values. The unset() functions resets a variable.

How do I re index an array in PHP?

The re-index of an array can be done by using some inbuilt function together. These functions are: array_combine() Function: The array_combine() function is an inbuilt function in PHP which is used to combine two arrays and create a new array by using one array for keys and another array for values.


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
)

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