0

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!";
}
1
  • 2
    Please trim the values and then check against "Banana" Commented Dec 12, 2018 at 9:37

3 Answers 3

5

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!";
}
Sign up to request clarification or add additional context in comments.

4 Comments

Or $array = explode(" : ", $var);
Yes @RiggsFolly You should post that as an answer. Way simpler
No actually I think your method s more reliable. In case they get $var = "Apple : Banana:Orange"; as a string
Well, now I just feel dumb :) Thank you so much tho! I also recommend anyone doing this to store each trimmed value in new variable: $value_a = trim($array[0]); $value_b = trim($array[1]);
4

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!

Comments

1

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

1 Comment

Sure, but trim version below feels simpler

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.