[thelist] stupid PHP question

Paul Waring paul at xk7.net
Thu Jul 7 09:17:04 CDT 2005

On Thu, Jul 07, 2005 at 09:43:16AM -0400, Nan Harbison wrote:
> What I don't understand is the syntax of this line:
> 	$row_count = is_array($row) ? count($row) : 0;
> I have spent hours looking through my PHP books, but can't find it. Can
> someone please explain what the question mark is doing? And the count($row)
> : 0?

It's the equivalent to writing:

if ( is_array($row) )
	$row_count = count($row);
	$row_count = 0;

In other words, the left hand side of the equals sign will be set to the
value of the left side of the colon if the expression before the
question mark is true, and the value of the right side of the colon
otherwise. It's basically a more compact way of assigning a value to a
variable based on the result of a boolean expression.

You can read a bit more about the ternary operator here:

As for the count($row) part, that just counts the number of entries in
the $row array, so for example if you had $row[0], $row[1] and $row[2],
count($row) would return 3. It works in the same way for associative
arrays, and it's useful when looping through all elements of an array
because you can do something like:

for ( $i = 0; $i < count($row); $i++ )
	// do something with $row[$i]

although the foreach operator might be more useful if you want to
iterate over an array. You can also do more fancy things with count,
such as counting recursively through an array.

More information can be found at:

Hope this helps.


Rogue Tory

More information about the thelist mailing list