Search code examples
phparraysstringif-statementexplode

PHP: Check if array key is specific string


I'm trying to create an if statement. based on the string of the

$var = "Apple : Banana";
$array = explode(":", $var);
print_r($array); //array([0] => 'Apple' [1] => 'Banana')

if ($array[1] == "Banana") {
  echo "Banana!";
}

Solution

  • The string has space before and after :, so array will be

    array(2) { 
        [0]=> string(6) "Apple " 
        [1]=> string(7) " Banana" 
    }
    

    You need to remove space from items using trim() and then compare it.

    $var = "Apple : Banana";
    $array = explode(":", $var);
    
    if (trim($array[1]) == "Banana") {
        echo "Banana!";
    }