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!";
}
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!";
}
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!";
}
$array = explode(" : ", $var);$var = "Apple : Banana:Orange"; as a string$value_a = trim($array[0]); $value_b = trim($array[1]);Your condition doesn't work because each element of array has space. You should remove excess spaces. You can use trim function to remove spaces and array_map function to apply trim in each element of the array.
For example:
$var = "Apple : Banana";
$array = array_map('trim', explode(":", $var));
if ($array[1] == "Banana") {
echo "Banana!";
}
result:
Banana!
You can do it by using preg_split and regex
$parts = preg_split('/\s+\:\s+/', $var);
Then on $parts you will get:
array(2) { [0]=> string(5) "Apple" [1]=> string(6) "Banana" }