I have switched from using this ternary operation to if/elseif/else, but I would really like to know why this doesn't work. I keep getting the error:
ErrorException [ Notice ]: Undefined property: stdClass::$error
If I were to switch the order of the conditions so that the $res->response piece was 3rd, then I get the same error but for that property instead. It makes no sense to me, and testing it on Codepad.org (which uses PHP 5.2) it works as expected: http://codepad.org/gwteijIe
Here's the test code in question:
$output = '{"error":{"message":"This is a test error"}}';
$res = json_decode($output);
$error = isset($res->response) ? $res->response->message :
isset($res->error) ? $res->error :
isset($res->error->message) ? $res->error->message :
$output;
echo $error;
(The reason why it checks for $res->error and $res->error->message is because the API we're using will return any one of the three conditions we're checking for. Disclaimer: it's not my API!)
Any insight as to why I am not getting the results I expect? Many thanks in advance for the help.
Edit:
To clarify, this is what I am trying to achieve:
if (isset($res->response))
{
$error = $res->response->message;
}
elseif (isset($res->error->message))
{
$error = $res->error->message;
}
elseif (isset($res->error))
{
$error = $res->error;
}
Don't nest ternary operator.
You see the error because of the order in which ternary operators are evaluated; it would be far better and more maintainable to just write it out like this:
if (isset($res->response)) {
$error = $res->response->message;
} elseif (isset($res->error)) {
if (isset($res->error->message)) {
$error = $res->error->message;
} else {
$error = $res->error;
}
} else {
$error = $output;
}
Your old code evaluates like this; even then it's non-obvious what really happens:
((isset($res->response) ? $res->response->message :
isset($res->error)) ? $res->error :
isset($res->error->message)) ? $res->error->message :
$output;
See also: Comparison Operators
Related
I'm having to manually edit a file that's whiting out my forum pages and the error that the PHP validator kicks out is: Can't Use Function Return In Write Context. The line in question is:
$canSeePrivateTopics = !empty($modSettings['PrivateTopics_enable']) ? allowedTo('can_always_see_private_topics') = true;
The surrounding code is:
$posts = array();
$canSeePrivateTopics = !empty($modSettings['PrivateTopics_enable']) ? allowedTo('can_always_see_private_topics') = true;
while ($row = $smcFunc['db_fetch_assoc']($request))
{
if (empty($canSeePrivateTopics) && !empty($row['private_users']))
{
$ptusers = PrivateTopics_decode($row['private_users']);
if (!empty($ptusers) && !isset($ptUsers[$user_info['id']]))
continue;
}
$row['body'] = parse_bbc($row['body'], $row['smileys_enabled'], $row['id_msg']);
I'm afraid I don't understand how to correct it, since I'm so very new at this. Any help would be so appreciated!
The syntax of your ternary expression seems to be incorrect. It should be
$canSeePrivateTopics = !empty($modSettings['PrivateTopics_enable']) ? allowedTo('can_always_see_private_topics') : true;
instead.
At the model of MVC pattern of codeigniter, I make some codes that is same at below.
function getBoardNum($option){
foreach($option as $key=>$content){
$this->db->where($key,$content);
//echo "$key $content";
}
if(isset($this->db->get('parsing_tb')->row()->num)){
$num = $this->db->get('parsing_tb')->row()->num;
return $num;
} else {
return false;
}
}
The problem is the isset at the if condition seems to not work.
To find out what is wrong, I used var_dump and such like confirming the $option data. But everything is okay...
Please let me know what is wrong! Thank you for reading.
Idk why isset() is not working, but you can try this instead :
//...
$query = $this->db->get('parsing_tb');
if ($query->num_rows() > 0)
{
$num = $this->db->get('parsing_tb')->row()->num;
return $num;
}
else
return false;
You should use isset to check if some variable is initialized - that means you check if it has any value.
even this case will yield TRUE:
$var = "";
if( isset( $var )){
echo TRUE;
}
In your code it looks like you are first trying to initialize it and assign some value to it and you use isset. You should use a different method for whatever you are trying to accomplish.
This question already has answers here:
Reference Guide: What does this symbol mean in PHP? (PHP Syntax)
(24 answers)
Closed 9 years ago.
if ($form->isValid()) {
// ... perform some action, such as saving the task to the database
$nextAction = $form->get('saveAndAdd')->isClicked()
? 'task_new'
: 'task_success';
return $this->redirect($this->generateUrl($nextAction));
}
Here is the link to the documentation
http://symfony.com/doc/current/book/forms.html
The class documentation says that it returns a bool.
What is the point of
? 'task_new'
: 'task_sucess';
That is called "ternary" and it's awesome:
This is assigning the value $nextAction based on a condition. The first part (after the =) is the condition, like an if statement, the second part (after the ?) is the value assigned if the condition is true, and the last part (after the :) is the value assigned if the condition is false.
//the condition
$nextAction = $form->get('saveAndAdd')->isClicked()
? 'task_new' //true value
: 'task_success'; //false value
It is a shorter way of writing this:
if ($form->get('saveAndAdd')->isClicked()) {
$nextAction = 'task_new';
}
else {
$nextAction = 'task_success';
}
So, here's some easy examples:
$foo = (true) ? 'True value!' : 'False value!';
echo $foo; //'True value!' of course!
$foo = (false) ? 'True value!' : 'False value!';
echo $foo; //'False value!' of course!
It's the Ternary operator. The syntax is as follows:
value = (condition) ? run if true : run if false;
In this case, if $form->get('saveAndAdd')->isClicked() is true, then task_new. Else task_success.
If could be rewritten like so:
if($form->get('saveAndAdd')->isClicked()) {
$value = "task_new";
} else {
$value = "task_success";
}
The ternary operator is a shorter form for an if statement.
The : is the "else" part.
Example in Java:
boolean bool;
true ? bool = true : bool = false;
It's a senseless example, but shows the ternary operator very well.
if the condition, here true is "true", then fill into the variable bool true, else false.
alternative if-statement in Java to the code example above:
boolean bool;
if(true)
bool = true;
else
bool = false;
This is a Ternary Operator which is a short hand if else statement. This is equivalent to
if($form->get('saveAndAdd')->isClicked()){
$nextAction = 'task_new'
else{
$nextAction = 'tassk_success'
}
This is the ternary opeator, a short-hand expression that works the same as an if
$value = someFunc() ? "whatever" : "the other"
is equivalent to
if (someFunc()) {
$value = "whatever";
} else {
$value = "the other";
}
This is equivalent to "if" and "else" statements.
This code :
$nextAction = $form->get('saveAndAdd')->isClicked()
? 'task_new'
: 'task_success';
is equivalent to this code :
if ( $form->get('saveAndAdd')->isClicked() )
{
$nextAction = 'task_new';
}
else
{
$nextAction = 'task_success';
}
I have a conflict regarding else condition. I can write a program in 2 ways.
Method 1
$msg = '';
if(cond)
{
$msg = 'success';
}
else
{
$msg = 'error';
}
Method 2
$msg = 'error';
if(cond)
{
$msg = 'success';
}
Can you please tell me which method is better and how? Thanks
Between the two, I'd choose the first one.
$msg = '';
if(cond) {
$msg = 'success';
} else {
$msg = 'error';
}
This is readable and clearly conveys what it's trying to do.
If the condition is true, the message will be success. If not, the message will be error.
But for something really simple as above, I'd use a ternary statement instead. It's very useful and can cut down code, but may make your code unreadable in some cases:
$msg = (cond) ? "success" : "error";
Pretty cool, right? Read more about ternary operators here.
Use the ternary operator:
$msg = (cond) ? 'success' : 'error';
I'd say the second one is better cause it's less lines and it has a default behavior. No matter what, you know that $msg will contain something, even if you add other checks down the road. However, I would use the Ternary operator in this case:
$msg = (cond) ? 'success' : 'error';
Code readability matters, so I'd use ternary operator when it really simplifies the look.
Consider this,
function foo($stuff) {
$var = null;
if ($stuff === true) {
$var = true;
} else {
$var = false;
}
return $var !== null ? true : false;
}
Since in this case, return $var !== null ? true : false is pretty short, it can be considered as "easy to read and understand".
Consider this,
function foo($stuff) {
$var = null;
if ($stuff === true) {
$var = true;
} else {
$var = false;
}
if ($var !== null) {
return true;
} else {
return false;
}
}
The same thing, but a little bit longer
Conclusion
if a condition isn't that long, it's okay to stick with ternary operators (Because of readability). But if its not, then you'd better stick with if/else
Also you should call this thing "Approach", not a "method", because a method is a function within a class.
I'd love to know what this means so I can google it as I see it all the time and it seems to be very useful
(($winstate==1)?'X':'O')
edit: The vars are irrelevant.
Thanks guys
That's called a ternary operator, it's PHP's only ternary operator, and it's shorthand for a conditional:
if($winstate == 1){
return 'X';
}else{
return 'O';
}
It's frequently used when the conditional test results in an assignment or returns something, in this case suppose you wanted to assign 'X' or 'O' to a variable $move, it's far more concise to write:
$move = ($winstate == 1) ? 'X' : 'O';
Look at Comparsion Operators
There's everything explained
<?php
// Example usage for: Ternary Operator
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];
// The above is identical to this if/else statement
if (empty($_POST['action'])) {
$action = 'default';
} else {
$action = $_POST['action'];
}
?>