[php] simple search using associative arrays
Greyruin
greyruin at gdurkin.com
Sun May 29 15:01:53 EST 2011
It looks good, all the same - but I think you need to add a flag for
"found" so that you have an error message in the event of a typo:
<?php
/*
file: SearchNameAge.php
called from SearchNameForm.php
*/
$ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";
foreach($ages as $name => $age)
{
echo "The name is $name and the age is $age <br />";
}
echo "let us search for Joe<br />";
// Assume "Joe" has not yet been found:
$found = false;
$searchname = "Joe";
foreach($ages as $name => $age)
{
if($name == $searchname)
{
echo "The name is $name and the age is $age <br />";
// Here he is, so note that fact (computers suffer from Alzheimers)
$found = true;
}
}
// Let the user know if we didn't find Joe:
if !$found
echo "Oops! We weren't able to find your Joe";
?>
Since your program is keyed to find a particular name, and won't pass
the debug stage until it does, these additions aren't strictly speaking
necessary. Even so, it never hurts to model completeness for students.
Nice one.
G
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.edulists.com.au/pipermail/php/attachments/20110529/1c03075a/attachment.html
More information about the php
mailing list