PDA

View Full Version : Search and List



tech_support
04-25-2007, 01:35 AM
Say I have an array:


$myarr = array('stir','cook','cake','mcdonalds','fry','rice','save','stir-fry');

If I enter "s" how would I get a list of everything that starts with "s" in that array?

Basically, I want it to search in the array, and list everything with "s" in it.

djr33
04-25-2007, 02:49 AM
$n=0;
foreach($myarr as $word) {
if (substr($word,0,1)=='s') {
$myarr2[$n] = $word;
$n++;
}
}

//Or, for just checking if S exists,
if (strpos($word,'s')!==FALSE) {

tech_support
04-25-2007, 04:30 AM
Thanks.
How would I make it so if a duplicate of the string appears it doesn't put it in the array?
eg. stir,stir,fry

codeexploiter
04-25-2007, 05:38 AM
Change the following line of djr33's code

if (substr($word,0,1)=='s') {
to the following line


if (substr($word,0,1)=='s' && !in_array($word,$myarr2)) {

Twey
04-25-2007, 08:39 AM
You can generalise this a bit more:
function search_array($arr, $begin) {
$r = array();
foreach($arr as $v)
if(substr($v, 0, strlen($begin)) === $begin && !in_array($r, $v))
array_push($r, $v);
return $r;
}Or use array_filter():
$newarr = array_unique(array_filter($arr, create_function('$v', 'return substr($v, 0, 1) === \'s\';')));

tech_support
04-26-2007, 06:36 AM
Thanks, but I don't think we need it that complex :)

Twey
04-26-2007, 10:15 AM
Well the second one's a single statement, it doesn't get much less complex than that :p