Forum Moderators: coopster
The following code:
<?php foreach ($option['value'] as $option_value) echo $option_value['name'] . " "; ?>
Outputs:
Silver Black Red Orange
How can I get it to output only "Silver" or whichever record is first in that output. I cannot truncate it to a certain char count because the first record will vary in chars.
<?php
foreach ($option['value'] as $option_value) {
echo "{$option_value[0]} ";
}
?>
As you can number arrays as well as use there 'name'. Arrays start from 0 not 1 (so if you use $arrayyou will get the second element). <edit> [1][edited by: PHP_Chimp at 8:24 pm (utc) on Feb. 21, 2008]
added the closing } to the code.
PHP_Chimp: I rec'd "Notice: Undefined offset: 0 in..."
cameraman: I'm interested in your reset method. Although I haven't been manipulating the array, it would be nice to have this trick under my belt. Would you be so kind as to show me how to output "silver" with a little more elaborate example. I tried:
<?php $option_value = each($option['value']);
echo $option_value['name'];?>
To which I rec'd no output...
echo "<pre>\$m =\n";
var_dump($m);
echo "\n\n\$one =\n";
$one = each($m);
print_r($one);
echo "\nagain\n";
$one = each($m);
print_r($one);
echo "\nafter reset\n";
reset($m);
$one = each($m);
print_r($one);
echo "</pre>";
You get an array that lists the element's key and value. If you replace the lines using each() above with:
list($key,$one) = each($m);
then $key will contain the element's key, and $one will be an associative array containing the element's value (it winds up being an array since the value went into ['name']). $one['name'] will be today when the array is first used and after reset(), and tomorrow when you hit it the second time (after 'again'). foreach() is a loop construct that goes through the contents of an array, whereas each() is a "one-time" hit.