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.... Quote Link to comment https://forums.phpfreaks.com/topic/290352-php-array/ Share on other sites More sharing options...
Solution ginerjm Posted August 8, 2014 Solution 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>"; Quote 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 (edited) $arr = $arr + array_fill_keys(range(0, max(array_keys($arr))), 0); ksort($arr); Edited August 8, 2014 by CroNiX Quote 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? Quote 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. Quote 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... Quote Link to comment https://forums.phpfreaks.com/topic/290352-php-array/#findComment-1487206 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.