subhomoy Posted August 8, 2014 Share Posted August 8, 2014 Hello everybody I am facing some problem with array.. I have a na array like this $arr = array( [0]=>1, [1]=>10, [2]=>166, [7]=>12, [15]=>1365, [20]=>1253, . . . . . [31]=>40 ); What i want is that to show the whole array. The keys consist of all the dates of a month.. If no specific dates exits then it will show 0 for that corresponding dates.. Like the above array does not contain keys [3]. [4], [5], .... I awant to show them as zero... Like this $arr = array( [0]=>1, [1]=>10, [2]=>166, [3]=>0, [4]=>0, [5]=>0, [6]=>0, [7]=>12, [15]=>1365, [20]=>1253, . . . . . [31]=>40 ); Any help will be greatly appreciated... Thank u in advance.... Link to comment https://forums.phpfreaks.com/topic/290352-php-array/ Share on other sites More sharing options...
ginerjm Posted August 8, 2014 Share Posted August 8, 2014 for ($I = 1; $I < $lastday; $I++) if (array_key_exists($I,$ar)) echo "$I is $ar[$I] <br>"; else echo "$I is 0<br>"; Link to comment https://forums.phpfreaks.com/topic/290352-php-array/#findComment-1487194 Share on other sites More sharing options...
CroNiX Posted August 8, 2014 Share Posted August 8, 2014 $arr = $arr + array_fill_keys(range(0, max(array_keys($arr))), 0); ksort($arr); Link to comment https://forums.phpfreaks.com/topic/290352-php-array/#findComment-1487195 Share on other sites More sharing options...
ginerjm Posted August 8, 2014 Share Posted August 8, 2014 Cronix - Not familiar with array_fill_keys() nor range() but after reading the manual I think there is a flaw in this. Your range will produce a set of values ending with whatever is the highest EXISTING key in the array. Then array_fill_keys assigns a 0 value to all of the indices in the range set. What about the days that were not in the original array higher than the existing max day? Link to comment https://forums.phpfreaks.com/topic/290352-php-array/#findComment-1487198 Share on other sites More sharing options...
CroNiX Posted August 8, 2014 Share Posted August 8, 2014 Yeah, I was just going by the example he posted. If he needs that he can just change max(array_keys($arr)) to the number of days in the given month. He also has a "0" day, not sure how that's possible if it's the days of the month. Link to comment https://forums.phpfreaks.com/topic/290352-php-array/#findComment-1487204 Share on other sites More sharing options...
subhomoy Posted August 8, 2014 Author Share Posted August 8, 2014 sharp eyes @croNix.. The key '0' should not be there... Btw thanks for the help guysss... Link to comment https://forums.phpfreaks.com/topic/290352-php-array/#findComment-1487206 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.