home

get_url

operators

strings

Sponsor001

 

Page created 18 May 2005, updated 13 June 2008.

OPERATORS

The highlighted part of the script below has always looked very confusing. This is an attempt to make it clearer. The code is explained using JavaScript, before the equivalent script in PHP.

JAVASCRIPT

<script type = "text/javascript">

var str = "";

var result = ( str ? true : false );

alert( result );

</script>

What happens is, if ' str ' equates to true, result will be assigned the value ' true '. Otherwise str is false, and result is assigned the value ' false '.

To understand the script better, change the value of ' str ', for example:

str = 0, str = 1, str = -1, str = " ", str = "0", str = "mp3science", str = true, str = false.

Also, change ( str ? true : false ) to ( str ? "true value" : "false value" ) or ( str ? "Red" : "Blue" )

Hopefully, with a little practice, the script will be easier to understand.

NOTES

This script only works if str = (true or false), which is the same as ( 1 or 0 ). In other words 1 = true, 0 = false. Some results, such as indexOf() string search, will always return true, because when a match isn't found, it returns - 1, which is true. See the article ' Strings ' for more information.

ALTERNATIVE METHOD

<script type = "text/javascript">

var str = "";

var result = false;

if ( str ){

result = true;

}

alert( result );

</script>

So in other words, result = ( str ? true : false ) is an easier way of writing an if statement block.

PHP

The following code does the same using PHP:

<?php

$str = " ";

$result = ( $str ? "true" : "false" );

echo( $result );

?>

There are however, some differences. With JavaScript, I was able to use true and false without quotes. So "true" and "false" are just strings in PHP. Another difference, the value "0" is true with JavaScript, but equals the number 0 in PHP, which is false. So although the scripts look very similar, there are some differences.