The ListContains function is a quick and easy function to use. The ListContains function determines the index of the first list element that contains the specified substring. If the substring can not be found in the list, The ListContains function will returns zero. This function will not ignore empty sets; thus the list "a,b,c,,,d" has 8 elements |
|
The Function: |
<php function ListContains($list,$substring,$delimiter=",") { $delimiter = substr($delimiter,1); $a = explode($list,$delimiter); $return = 0; for($i=0;$i< count($a);$i++) { if(strstr($a[$i],$substring)) { $return = $i + 1; } } return $return; } ?> |
Usage: |
Using the ListContains function is simple: |
<?php $list = "one,two,three"; $substr = "two" ; if(ListContains($list,$substr) > 0) { echo $substr . " found at position " . ListContains($list,$substr): } ?> |
The output of this function will be: two found at position 2
2 comments:
Hey man,
I stumbled across your blog today as I was looking for this exact function for PHP!
A couple things I noticed:
$a = explode($list,$delimiter);
I believe should be
$a = explode($delimiter,$list);
Also, take this list for example:
$list = "tester,foot,test,footer,nothinghere";
If I'm looking for 'foot', the function will return 4 instead of 2, since the function continues looping through the array even after finding 'foot', and because 'footer' contains 'foot'.
So this is what I did:
<?php
function ListContains($list,$substring,$delimiter=",")
{
$delimiter = substr($delimiter,0);
$a = explode($delimiter,$list);
print_r($a);
$return = 0;
for($i=0;$i< count($a);$i++)
{
if(strstr($a[$i],$substring))
{
//$return = $i + 1;
return $i;
}
}
return $return;
}
}
?>
You'll also noticed that I changed
$delimiter = substr($delimiter,1);
to
$delimiter = substr($delimiter,0);
since PHP sees the ',' as index 0 and not 1.
Hope this helps, and keep up the great work. I look forward to seeing more functions :)
Oops, I forgot to take out the "print_r($a);"
Post a Comment