0

how can i compare multiple data using php

for example i have a variable $foo , the data assigned to it varies . if there are four different data can be assigned to variable $foo , like :" car , van,bus or bicycle"

how can i use the if statement to check which data is assigned to $foo?

normally if i have two data i will use

if($foo == 'firstdata'){
   //execute something as this is the first data
}
else{
   //this is the second data!
}

if there's 3 data i will use elseif statement.

but now 4 data , what can i use ? or can i use elseif as many times as i want??

2 Answers 2

4

There's no practical limit to how many if/elseif/elseif/elseif you can chain together. Another alternative is to use a switch statement:

switch ($foo) {
   case 'firstdata':
      ... do something with firstdata ...
      break;
   case 'car':
      ... do car stuff
      break;
   case 'van':
      ... do van stuff
      break;
   ...
   default:
      ... do stuff with an unknown datum
}
Sign up to request clarification or add additional context in comments.

1 Comment

While you can in fact use elseif as many times as you like I would recommend this approach in a lot of cases, particularly the one you called out.
1

Yes, you can use elseif as many times as you want, or you can use the switch statement .

Comments

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.