Jump to content

[SOLVED] need syntax format


kucing

Recommended Posts

Hi all..

 

I am having problem with proper syntax format.

 

If i am not mistaken this syntax is right

$myVar[$i]["var"] = ($a>1?$a=true:a=false);

 

but when i try to make some change like this

$myVar[$i]["var"] = (($a>1?$a=true:a=false)?$b=true:b=false);

 

it doesn't seems to work

As I want something like when the first parameter is true then the next parameter should work.

 

Thanks :)

I appreciate your help

 

Link to comment
Share on other sites

I don't think either is right. I'm not too familiar with the ternary, but I think it needs to be like this:

$myVar[$i]["var"] = ($a>1?true:false);

 

$a=true and $a=false will both return true, so in your first one it will always be true, because you get the value of that operation.

Check out the example on this page:

http://us2.php.net/ternary

Example 15.3. Assigning a default value

 

And this one:

Note:  Is is recommended that you avoid "stacking" ternary expressions. PHP's behaviour when using more than one ternary operator within a single statement is non-obvious:

Example 15.4. Non-obvious Ternary Behaviour

Link to comment
Share on other sites

I would also just consider using an if statement, especially since you are trying to set 3 different variables at once ($a, $b, $myVar). Someone might be able to clarify, but I believe the ternary is generally used to set the outside variable. For example, in this case, it is checking $a and then setting $myVar.

 

<?php
$a = 0;
$myVar = ($a > 1) ? true : false;
echo $myVar; //Displays nothing
?>

 

 

 

Link to comment
Share on other sites

$myVar = ($a > 1);

 

Wouldn't this do the same?

 

monk.e.boy

 

Actually, no. I just tried it because you piqued my interest, but that method only assigns a value to $myVar upon a TRUE comparison. It would be much safer the way thorpe shows.

Link to comment
Share on other sites

but that method only assigns a value to $myVar upon a TRUE

 

Yes but no value is also the booleen FALSE.

 

True, but typically when you echo the boolean FALSE, it prints as a '0' so you know you have the value stored. This does not.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.