Forum Moderators: coopster

Message Too Old, No Replies

How to output only first record of array

         

jomoweb

8:09 pm on Feb 21, 2008 (gmt 0)

10+ Year Member



I'm sure this is really simple, but my PhP gills are merely damp right now.

The following code:

<?php foreach ($option['value'] as $option_value) echo $option_value['name'] . "&nbsp;"; ?>

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.

adb64

8:22 pm on Feb 21, 2008 (gmt 0)

10+ Year Member



echo $option['value'][0]['name'];

PHP_Chimp

8:24 pm on Feb 21, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Try -

<?php
foreach ($option['value'] as $option_value) {
echo "{$option_value[0]}&nbsp;";
}
?>

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>
added the closing } to the code.

[1][edited by: PHP_Chimp at 8:24 pm (utc) on Feb. 21, 2008]

cameraman

8:26 pm on Feb 21, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



If the array is associative and you have no idea which is the first element:
$option_value = each [php.net]($option['value']);

If you've been doing things with the array, each() may not return the very first element - you can make sure it does by using reset() [php.net] just prior to each().

jomoweb

9:04 pm on Feb 21, 2008 (gmt 0)

10+ Year Member



ad64: Works perfectly, very simple!

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...

cameraman

12:58 am on Feb 22, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



for($i = 0; $i < 5; $i++)
$m["index_$i"]['name'] = date('l',strtotime("+$i days"));

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.