A community in which webmasters can ask for help with topics such as PHP coding , MySQL , IT jobs, web design, IT security.
Current location:homephp forumphp talk in 2009 yearHow can I add missing index in an array in php? - page 1
User InfoPosts
How can I add missing index in an array in php?#1
Example:

I have and array like this:

Array(
[0] => Apple
[2] => Orange
[5] => Pear
[8] => Pear
)

there are a function to complete the missing indexes: 1,3,4,6,7????

posted date: 2009-04-07 21:33:00


Re: How can I add missing index in an array in php?#2
I had made out the solution of this problem. click to view my topic...

hope that hepls.

posted date: 2009-04-07 21:33:01


Re: How can I add missing index in an array in php?#3
If what you(re trying to do is reorder the array so you getArray( [0] => Apple [1] => Orange [2] => Pear [3] => Pear )Just create a new Array and copy the values into it. It will allocate new indexes sequentiallyi.e. $new_array = array();for( $value in $old_array ) $new_array[] = $value;

posted date: 2009-04-07 21:45:00


Re: How can I add missing index in an array in php?#4
you could try a for() from the lowest index to the highest and complete if it(s emptyfor($i = 0 ;$i <= 8 ; $i++) {//if it(s not setif(!isset($array[$i])){//set to empty$array[$i] = "";}}Additionally you could count first the number of elements on the array and wrap it in a function function completeIndexes($array) { $total = count($array); for($i = 0 ;$i < $total ; $i++) { //if it(s not set if(!isset($array[$i])) { //set to empty $array[$i] = ""; } }return $array; }

posted date: 2009-04-07 21:48:00


Re: How can I add missing index in an array in php?#5
for($i=0;i<count($array);++$i){ $array[$i] = isset($array[$i])? $array[$i] : ((;}It just fills the missing keys with an empty string, though. Not sure if this suits you.EditJust noticed Perr0_hunter wrote pretty much the same thing before I did :P

posted date: 2009-04-07 21:49:00


Re: How can I add missing index in an array in php?#6
use array_Values() instead of your for loop

posted date: 2009-04-08 00:37:00


Re: How can I add missing index in an array in php?#7
This should be faster for larger arrays. For smaller arrays any method will do.$existingKeys = array_keys($array);//you can use any value instead of null$newKeys = array_fill_keys(range(min($existingKeys), max($existingKeys)), null);$array += $newKeys;//optional, probably not neededksort($array);

posted date: 2009-04-08 00:41:00


select page: « 1 »
Copyright ©2008-2017 www.momige.com, all rights reserved.