hi all,

i have a problem with the array search in php.I have an array like ("apple","orange","mango") and i have a variable as $var="apple 1".
Now i want to search this $var is exist in the above array and if so want to retreive that element from the array?

that is if $var="apple 1"; i want to check whether any element like 'apple 1' is exist in the array or not. and i want to echo the 'apple' from the array

can u plz help me...
thanx in advance...

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'.

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;
  }

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 />";
	} 
}
?>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.