Sunday, January 13, 2008

ListFind / ListFindNoCase

The ListFind and ListFindNoCase are identical functions other than the obvious reason; one is case sensative and the other is not. If you use list to store data or move data, the ListFind function is incredibly useful. Also, the ListFind function works well when rerading comma seperated lists or scraping data from other websites.

The Function:


<?php

function ListFind($list,$value,$delimiter=",")
{
$delimiter = substr($delimiter,1);
$a = explode($delimiter,$list);
for($i=0;$i<count($a);$i++)
{
if( strstr($a[$i],$value))
{
return true ;
}
}
return false;
}

function ListFindNoCase($list,$value,$delimiter=",")
{
$a = explode($delimiter,$list);
for ($i=0;$i<count($a);$i++)
{
if(stristr($a[$i],$value))
{
return true;
}
}
return false;
}


?>

Usage:

<?php
$list = "Car,Truck,Boat,Plane,Train" ;
$find = "car";
if(ListFind($list,$find))
{
echo $find . " found!";
}
?>


Using the ListFind to find 'car' will fail since the ListFind is case sensetive. However, the ListFindNoCase will do the trick!

<?php
$list = "Car,Truck,Boat,Plane,Train" ;
$find = "car";
if( ListFindNoCase($list,$find))
{
echo $find . " found!";
}
?>

The result in this case will be : car found!

5 comments:

Valkyrie said...

It amazes me sometimes the functions that simply aren't in other programming languages. Thanks for these functions. They will help me develop this project a whole lot faster.

Anonymous said...

your stristr function is backwards. it should be:

if(stristr($value, $a[$i])) {

Anonymous said...

I stumbled across this and I needed it, but anyone else who discovers it should know that the line in ListFind() that says:

$delimiter = substr($delimiter,0);

should be:

$delimiter = substr($delimiter,1);

In php, first digit is 0, not 1.

Thanks!

Anonymous said...

A better way for me

public function listFind($list, $value, $delimiter=",")
{
$arr = explode($delimiter, $list);

for($i=0; $i<count($arr); ++$i)
if(strcmp($arr[$i], $value) == 0)
return true;

return false;
}

public function listFindNoCase($list, $value, $delimiter=",")
{
$arr = explode($delimiter, $list);

for($i=0; $i<count($arr); ++$i)
if(strcmp(strtolower($arr[$i]), strtolower($value)) == 0)
return true;

return false;
}

Anonymous said...

Wouldn't this be most concise?


function ListFind($l,$s,$d=','){return in_array($s,explode($d,$l));}
function ListFindNoCase($l,$s,$d=','){return ListFind(strtolower($l),strtolower($s),$d);}