0
echo '<input type="checkbox" name="check_list[]" value="OMG" checked>';

this way will display a normal checkbox with checked. My question is that is it possible to put a if else inside the checkbox?

For example,

echo '<input type="checkbox" name="check_list[]" value="OMG" "if(2>1){ echo "checked";};" >'; 

The reason i want to do this is because I have a array with 6 data, if certain condition meet, the checkbox will be checked. If the echo method i mentioned above is invalid, so what's the correct way of doing that?

$zzz[1]="western food";
$zzz[2]="chinese food";
$zzz[3]="mix food";
$zzz[4]="japanese food";
$zzz[5]="korean food";
$zzz[6]="italian food";

2 Answers 2

2

You can do this easily by concatenating your string with a ternary operator:

echo '<input type="checkbox" name="check_list[]" value="OMG" ' . ((2>1) ? "checked" : ""). '>';

The ternary operator works this way:

(2>1) ? 'checked' : ''

2>1 is considered a boolean expression (that returns either true or false). 'checked' is the result in case the boolean expression is true, and an empty string '' if it is false.

Sign up to request clarification or add additional context in comments.

2 Comments

the output is "checked" . any example that is the checkbox being checked after the if condition meet?
@gosulove Check it out now :)
1

Corrected version of your code

echo '<input type="checkbox" name="check_list[]" value="OMG" '.(2>1)?"checked":"".' >'; 

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.