I want search one string and get related values, but in test the function, in each times search words(Title
Or Would
Or Post
Or Ask
) displaying(give) just one output Title,11,11
!!!! how can fix it?
// test array
$arr = array('Title,11,11','Would,22,22','Post,55,55','Ask,66,66');
// define search function that you pass an array and a search string to
function search($needle,$haystack){
//loop over each passed in array element
foreach($haystack as $v){
// if there is a match at the first position
if(strpos($needle,$v) == 0)
// return the current array element
return $v;
}
// otherwise retur false if not found
return false;
}
// test the function
echo search("Would",$arr);
The issue lies in strpos
. http://php.net/manual/en/function.strpos.php
The haystack is the first argument and the second argument is the needle.
You should also do a ===
comparison for getting 0.
// test array
$arr = array('Title,11,11','Would,22,22','Post,55,55','Ask,66,66');
// define search function that you pass an array and a search string to
function search($needle,$haystack){
//loop over each passed in array element
foreach($haystack as $v){
// if there is a match at the first position
if(strpos($v,$needle) === 0)
// return the current array element
return $v;
}
// otherwise retur false if not found
return false;
}
// test the function
echo search("Would",$arr);