4
Contributors
3
Replies
4
Views
7 Years
Discussion Span
Last Post by nav33n
0

The function array_search retrieves the key for a supplied value in an array if found, or false otherwise. This means that you can use it to search any array that does not contain boolean values. So, to search your array I would do the following:

$arr = array(1 => "apple",2 => "orange",3 => "mango");
$var = "apple 1";
$key = array_search( $var, $arr );
if( $key === false ) // note the use of identical rather than equal
{
  // not found, do something...
}
else
{
  // found, at index $key so
  $found = $arr[ $key ];
}

Note however that 'apple 1' is not in that array, so will not be found, because 'apple 1' does not equal 'apple'.

0

Also the following will do the same job:

$arr = array(1 => "apple",2 => "orange",3 => "mango");
$var = "apple 1";
if(!in_array( $var, $arr )) {
  // not found, do something...
  } else {
  // found
  $found = $var;
  }
0

I don't know if this is what you meant.

<?php
$arr = array("apple","mango","grapes");
$var = "apple 1";
foreach($arr as $value) {
	if(strpos($var,$value) !== false) {
 		echo $value ." is the closest match for ".$var."<br />";
	} 
}
?>
This article has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.