Creating multidimensional arrays
Emmanuel. M. Decarie
emm at scriptdigital.com
Wed May 14 08:57:44 EDT 2003
Hello,
I have this little function that work well for me, but I was
wondering if it could be optimized. I use it to set the default value
of checked radio buttons. Also, while doing this function, I
discovered that PHP can autoinstantiate associative arrays in depth.
For ex.
$ar = array ();
$ar['one']['two']['three'] = 'hello world';
echo $ar['one']['two']['three'];
--> hello world
I must say that PHP's array are one of the nicest feature of the language.
--------------------------------------------------------
Here's what it look inserted in the HTML page:
--------------------------------------------------------
<hr>
<form>
Are you ugly?
Yes
<input type="radio" name="choice_1" value="1" <?php echo
$radioGroup['1']['1'] ?>>
No
<input type="radio" name="choice_1" value="1" <?php echo
$radioGroup['1']['2'] ?>>
<hr>
Are you tall?
Yes
<input type="radio" name="choice_2" value="1" <?php echo
$radioGroup['2']['1'] ?>>
No
<input type="radio" name="choice_2" value="1" <?php echo
$radioGroup['2']['2'] ?>>
<hr>
Are you funny?
Yes
<input type="radio" name="choice_3" value="1" <?php echo
$radioGroup['3']['1'] ?>>
No
<input type="radio" name="choice_3" value="1" <?php echo
$radioGroup['3']['2'] ?>>
</form>
--------------------------------------------------------
And here's the function:
--------------------------------------------------------
function assignValues ($maxOutArrays, $maxInArrays, $arSelection) {
$counter1 = 1;
while ( $counter1 <= $maxOutArrays ) {
$counter2 = 1;
while ( $counter2 <= $maxInArrays ) {
if ( !isset ($arSelection[$counter1][$counter2]) ) {
$arSelection[$counter1][$counter2] = '';
}
$counter2++;
}
$counter1++;
}
return $arSelection;
}
$radioGroupDefaultValues['1']['2'] = 'checked';
$radioGroupDefaultValues['2']['1'] = 'checked';
$radioGroupDefaultValues['3']['1'] = 'checked';
$radioGroup = assignValues (3, 2, $radioGroupDefaultValues);
--------------------------------------------------------
And the output show with var_dump ($radioGroup)
--------------------------------------------------------
array(3) {
[1]=>
array(2) {
[2]=>
string(7) "checked"
[1]=>
string(0) ""
}
[2]=>
array(2) {
[1]=>
string(7) "checked"
[2]=>
string(0) ""
}
[3]=>
array(2) {
[1]=>
string(7) "checked"
[2]=>
string(0) ""
}
}
Now I have a big form with 50 radio buttons in 10 groups of 5 radio
buttons. I didn't benchmark this function, it seems that it run well,
but if there is a better way to do it, I'd like to hear it.
TIA
--
______________________________________________________________________
Emmanuel Décarie / Programmation pour le Web - Programming for the Web
Radio UserLand/Frontier - Perl - PHP - Javascript <http://scriptdigital.com/>
Blog: <http://blog.scriptdigital.com> - AIM: scriptdigital
More information about the talk
mailing list