Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to re-key array with non-sequential numeric keys

Tags:

arrays

php

I have an array:

Array (  [0] => ololo  [2] => test  [3] => haha  [7] => nice ) 

How can I change the indexes of the array to this:

Array (  [0] => ololo  [1] => test  [2] => haha  [3] => nice ) 
like image 742
kopaty4 Avatar asked Jun 16 '11 19:06

kopaty4


People also ask

How do you replace array keys?

The array_replace() function replaces the values of the first array with the values from following arrays. Tip: You can assign one array to the function, or as many as you like. If a key from array1 exists in array2, values from array1 will be replaced by the values from array2.

How do I reindex an array?

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.

What is the use of Array_flip () function?

The array_flip() function flips/exchanges all keys with their associated values in an array.


2 Answers

From PHP.net:

array_values() returns all the values from the input array and indexes the array numerically.

Source

$arr = array_values($arr); 
like image 159
Paul DelRe Avatar answered Sep 18 '22 15:09

Paul DelRe


array_values() is probably what you want. See: http://php.net/function.array-values

$myArray = array_values($myArray); 
like image 27
Sean Avatar answered Sep 18 '22 15:09

Sean