1
$meal_type= "Free Breakfast|Free Wireless";
if ($meal_type != '' && $meal_type !='None') {
    $meal = explode('|', $meal_type);

    $meal = array_search('Breakfast',$meal);

    $meal = $meal_type;
} else {
    $meal= 'No Breakfast';
}
echo $meal;

This is my code. here i want to search Breakfast in the array and return searched value, if not found return No Breakfast.

Here i was explode string to array with | symbol and returned array search Breakfast if exist return funded array value else echo No Breakfast value.

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
Niranjan
  • 43
  • 6

2 Answers2

3

A simple foreach() will do the job:-

<?php
$match_counter =0;
$array = Array
(
    0 => 'Free Breakfast',
    1 => 'Free Wireless Internet'
);
$search = 'Breakfast';

foreach($array as $arr){
    if(stripos($arr,$search) !==false){
        echo $arr.PHP_EOL;
        $match_counter++;
    }
}
if($match_counter ==0){
    echo 'No '.$search;
}

Output:-

https://3v4l.org/ogOEB (occurrence found)

https://3v4l.org/AOuTJ (occurrence not found)

https://3v4l.org/NTH1W (occurrence found more than one time)

Reference:- stripos()

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
2
<?php
$array = array('Free Breakfast','Free Wireless Internet');

$string = 'Breakfast';
foreach ($array as $a) {


    if (stripos($a, $string) !== FALSE) {  
        echo  $string; 
        return true;
    }
}
echo "No" .$string;
return false;

?>

You can also use stripos() for case-insensitive.

case 1 : if array contains multiple same values

<?php
$array = array('Free Breakfast','Free Wireless Internet' ,'breakfast time');

$string = 'Breakfast';
$flag=true;
foreach ($array as $key=> $a) {

    if (stripos($a, $string) !== FALSE) {  
        $flag = false;

        echo  $string." contain in key position ".$key.'<br>'; 
        //return true;
    }
}
if($flag)
{
echo "No" .$string;
}



?>

sradha
  • 2,216
  • 1
  • 28
  • 48
  • 1
    Your answer correct for current scenario, but it will not cover all occurrences, if presented more than one time inside the array:-https://3v4l.org/ND0IF – Alive to die - Anant Jan 02 '19 at 08:26
  • @AlivetoDie I added some code for other cases, I think it will be helpful in other cases. – sradha Jan 02 '19 at 08:36