mistery_girl mistery_girl - 6 months ago 17
PHP Question

Create associative array with numbers in php - merge 3 arrays

I'm trying to create dropdown from associative array starting with:

None
=>
None


after that numbers from
01
to
24
in format -> 01, 02, 03...10,11...24
and finally add:

25+
=>
25+


Keys and values of dropdown should be the same.

I tried the following:



$format_numbers1 = array();
$format_numbers1['None'] = 'None';
for($i=1;$i<=9;$i++) {
$numbers[] = $i;
}

foreach($numbers as $number) {
$n = str_pad($number, 2, '0', STR_PAD_LEFT);
$format_numbers2[$n] = str_pad($number, 2, '0', STR_PAD_LEFT);
}
for($j=10;$j<=24;$j++) {
$format_numbers3[$j] = $j;
}
$format_numbers_new = array_merge($format_numbers1, $format_numbers2);
$format_numbers = array_merge($format_numbers_new, $format_numbers3);
$format_numbers['25+'] = '25+';





But I get this output:



array(26) { ["None"]=> string(4) "None" ["01"]=> string(2) "01" ["02"]=> string(2) "02" ["03"]=> string(2) "03" ["04"]=> string(2) "04" ["05"]=> string(2) "05" ["06"]=> string(2) "06" ["07"]=> string(2) "07" ["08"]=> string(2) "08" ["09"]=> string(2) "09" [0]=> int(10) [1]=> int(11) [2]=> int(12) [3]=> int(13) [4]=> int(14) [5]=> int(15) [6]=> int(16) [7]=> int(17) [8]=> int(18) [9]=> int(19) [10]=> int(20) [11]=> int(21) [12]=> int(22) [13]=> int(23) [14]=> int(24) ["25+"]=> string(3) "25+" }





Dropdown keys from 10 to 24 aren't correct.

Answer

For the range of 10..24 you're using integers as your keys, instead of strings:

for ($j = 10; $j <=24; $j++) {
    $format_numbers3["$j"] = "$j";
    # here ----------^--^----^--^
}

But frankly, you're over-complicating things. str_pad can handle values it doesn't need to pad, so you can handle all the numbers 1..24 in a single loop:

$format_numbers = array();
$format_numbers['None'] = 'None';
for ($i = 1 ;$i <= 24; $i++) {
    $n = str_pad($i, 2, '0', STR_PAD_LEFT);
    $format_numbers2[$n] = $n;
}
$format_numbers['25+'] = '25+';