I have a method that someone helped me with. Not sure what it means
echo ( $info['Ans_Answer'.$i]) ? " checked" : ""; I have a method that someone helped me with. Not sure what it means
echo ( $info['Ans_Answer'.$i]) ? " checked" : ""; As already pointed out, that line uses PHP’s ternary operator — a compact if/else that returns one expression when a condition is true and another when it’s false. In this thread the pattern is being used to conditionally output an HTML attribute fragment when a value in an array is truthy.
A couple of practical points that are easy to miss:
PHP’s notion of “truthy”/“falsy” includes values such as false, 0, 0.0, "0", "", NULL and an empty array. If your array stores numeric 0 for “not checked”, the ternary will treat that as false. See the PHP docs on boolean type conversions for details (php.net boolean types).
If the array key might not exist, you’ll get a notice unless you supply a default. In modern PHP use the null coalescing operator to avoid that; otherwise use isset() first. Example pattern:
$flag = $row['answers'][$i] ?? false;
echo $flag ? ' checked="checked"' : ''; Avoid nesting ternaries without parentheses — the result can be confusing. For readability and maintainability, prefer a short if block when the logic gets more than a simple on/off. For HTML checkboxes remember attribute formats: HTML5 accepts a bare checked while XHTML commonly uses checked="checked" (see MDN for input checkbox attribute details: MDN input checkbox).
For the original poster, , the quick takeaway is: it’s shorthand conditional output. For robustness, add a presence/default check (or use PHP 7+ ??) and use explicit comparisons if you must distinguish "0" from 1.
Jump to Post— Ezzaral 2,714Why not ask them then? If they "helped", they should be able to tell you quite easily what it is and why they did it that way.
Why not ask them then? If they "helped", they should be able to tell you quite easily what it is and why they did it that way.
well it was ages ago. I have to spend time looking for the thread. and I though someone out there might just know.
only part I dont get it
? " checked" : "";
It's a ternery operator - shorthand for if/else.
echo ( $info['Ans_Answer'.$i]) ? " checked" : ""; Is short for:
if($info['Ans_Answer'.$i]){
echo " checked";
}else{
echo "";
} Thank you. Thats all I needed to know..
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.