Re: Help with array / list looping syntax

From: Date: Wed, 30 Jun 2004 03:05:54 +0000
Subject: Re: Help with array / list looping syntax
References: 1 2  Groups: php.general 
Request: Send a blank email to php-general+get-189265@lists.php.net to get a copy of this message
On Wed, 30 Jun 2004 00:58:32 +0000 (GMT), Philip Olson wrote: >>> I need some help with a looping syntax. In english, "a" is used before >>> words that begin with consonants - "an" is used before words that start >>> with vowels. I'm trying to create a loop that checks this state and inserts >>> the correct word in the echo line. Below is the sloppy version of what I'm >>> trying to do... >>> >>> <?php >>> if (substr($table['field'], 0, 1)=="a") OR >>> (substr($table['field'], 0, >>> 1)=="e") OR (substr($table['field'], 0, 1)=="i") OR >>> (substr($table['field'], 0, 1)=="u") OR >>> (substr($table['field'], 0, >>> 1)=="y") } >>> echo 'Member has an ' . $table['field'] . ' who is...'; >>> } else { >>> echo 'Member has a ' . $table['field'] . 'who is...'; >>> } >>> ?> >>> >>> There's got to a cleaner way to do this. Perhaps using a list or array >>> containing the vowels and steping through it checking the first letter of >>> the field contents against each member of the list. But, I don't know how >>> to code this system. Please help. >>> >> >> How about this? >> >> $vowels = array('a', 'e', 'i', 'o', 'u'); >> echo 'Member has a'.(in_array($table['field'][0], $vowels) ? >> 'n' : >> '').' '.$table['field'].' who is...'; > > Yet another solution (just for fun): > > $vowels = 'aeiou'; > if (false !== strpos($vowels,strtolower($table['field']{0}))) echo 'n'; > > Regards, > Philip Thank you for your suggestions. I know it's not as elegant as your suggestions, but I settled on the following because it's easy for me to read and understand when I view the code later. I also listed both upper and lower case vowels in the array because according to the PHP Manual, in_array() is case sensitive. <?php $vowels = array('a','e','i','o','u','y','A','E','I','O','U','Y'); if (in_array(substr($table['field'], 0, 1),$vowels)) { echo 'Member has an ' . $table['field'] . ' who is...'; } else { echo 'Member has a ' . $table['field'] . ' who is...'; } ?> Thanx again, Robb -- Robb Kerr Digital IGUANA

« previous php.general (#189265) next »