Jump to content
Larry Ullman's Book Forums

Confused By The Ternary Operator In This Code


Recommended Posts

This is from page 258.

 

I understand how ternary operators work usually, but I don't get the logic in the 4th line below and the explanation in the book wasn't sufficient for me.

 

As far as I can read it, it says if "qty" is greater or equal than 0, use qty, otherwise use 1. but that doesn't make sense to me because then how does "1" ever get chosen?

 

And where does the array come from in that line? And how do the filters work?

 

Can someone write out the processing steps that take place in that line with the filters and the ternary operator.

 

First, it does this...

 

Then....

 

Then....

 

foreach ($_POST ['quantity'] as $sku => $qty) {
list($sp_type, $pid) = parse_sku($sku); 
if (isset($sp_type, $pid)) {
$qty = (filter_var($qty, FILTER_VALIDATE_INT, array('min_range' ➥=>0)))?$qty:1; 

$r = mysqli_query($dbc, "CALL update_cart('$uid', '$sp_type', ➥$pid, $qty)");

Link to comment
Share on other sites

I don't see this code on page 258, but anyway, I think your interpretation is correct:

 

There is an array called quantity in the POST superglobal. The SKUs are the indices, and $qty is the value of those SKUs (the number of items available for that SKU). Then the SKU is broken up into two parts, the $sp_type (I guess the product type) and the product ID. After that, if both of those are set, then quantity is checked to see whether it is a valid, positive integer (i.e., an integer starting from 0). If it is, then $qty remains unchanged, but if, for some reason, $qty is not an integer or is negative, then it's set to 1.

 

I guess the point is that the thing being evaluated in the ternary operation is the filter_var function with its arguments.

 

Hope that makes sense.

  • Upvote 1
Link to comment
Share on other sites

To expand on the latter part. The filter extension is fairly new to PHP and is used to validate ir santize various input forms. Such as emails, integers, floats etc. Here is a link for the section on the manual, it gives you all the different types availabe. Worth a quick squiz. (colloquial for look where I live) ;)

 

PHP Filter

  • Upvote 1
Link to comment
Share on other sites

 Share

×
×
  • Create New...