Ternary ignores first condition - php

Why is my ternary ignoring the first condition ($order->status === "prepairing") ?
It always skips the first condition when checking the order status and immediately goes toward the second (and always see's it as true)
$messageMiddle = ( ($order->status === "prepairing") ? " your prder is being prepared. Make your way towards the store."
: ($order->status === "complete") ?' your order is done! Please show your order-code at the store.'
: ' thank you for ordering ');

You need to group every next expression in parenthesis as follows. You forgot to enclose the second ternary expression in parentheses.
$messageMiddle = ($order->status === "prepairing") ? " your order is being prepared. Make your way towards the store." :
(($order->status === "complete") ? ' your order is done! Please show your order-code at the store.' : ' thank you for ordering ');
But you should avoid this approach anyways.

A better way to react to the status of an order would be a switch statement. Like this:
switch ($order->status) {
case "preparing" : $messageMiddle = " your order is being prepared. Make your way towards the store.";
break;
case "complete" : $messageMiddle = " your order is done! Please show your order-code at the store.";
break;
default : $messageMiddle = " thank you for ordering ";
break;
}
It is easy to see how you can extend this to react to other status words.
Note that I changed `"prepairing" to "preparing".
One of the things programmers strive for is succinct code. However, shorter code is not always better code. It might be less readable and more difficult to maintain and extend.

Related

ifelse in echo statement

I have code as bellow :
number_format(($hasilz->harga>100000 ? $hasilz->harga+2000 :
($hasilz->harga>300000 ? $hasilz->harga+4000 :
($hasilz->harga>400000 ? $hasilz->harga+8000 :
$hasilz->harga+10000))), 0, ',', '.')
this code result and read +2000 and +10000 only
any idea ?
Let's see what you got there (simplified):
if (hagara > 100000) {
harga+2000
} else if (hagara > 300000) {
hagara+4000
} else if (hagara > 400000) {
hagara+8000
} else {
hagara+10000
}
If you write it like this, its easy to see. hagara is either >100000 which results in +2000 or it is less, then it results in +10000.
In other words, the two else if will never be true, because if they were, the first if would already be true.
I think this is also a good example, when you should NOT use the tenary operator. It just makes it really hard to read and understand... sometimes the good old it-approach ist just the better solution. ;)
EDIT: To answer the question, you have to use a different order of the if-statements, beginning with the biggest one (or write them completely different). However, as already mentioned, you shouldn't do that.

Choosing more options with intval( $row)

I am trying to have this function working with 1 of 3 or more results (like "Yes, NO, Why not, Maybe" but i am not able to find a solution
$row['Funcionario'] = ( intval( $row['Funcionario']) == 1) ? "Yes" : "No";
The code above only gives me 2 possibilities:
Yes ($row['Funcionario'] == 1 ) or No ($row['Funcionario'] != 1)
How do I show Why not if $row['Funcionario'] == 2 or Maybe if $row['Funcionario'] == 3?
Easy way:
Define an array...
$answers = ["No", "Yes", "Why not", "Maybe"];
And get from it...
$row['Functionario'] = $answers[$row['Functionario']];
If the array is one-time use (ie. not used by other fields that may have these values), you could shorten it to:
$row['Functionario'] = ["No", "Yes", "Why not", "Maybe"][$row['Functionario']];
Readability may vary. Consider adding whitespace and/or comments to explain what's going on.
You should look into switch statements
switch ($row['Funcionario']) {
case 1:
echo 'This code will be executed if $row[\'Funcionario\'] is 1';
break;
case 2:
echo 'This code will be executed if $row[\'Funcionario\'] is 2';
break;
case "Yes":
echo 'This code will be executed if $row[\'Funcionario\'] is Yes';
break;
default:
echo 'This code will be executed if $row[\'Funcionario\'] is not any of the values before
}
You can replace the values after case with anything you want, and the following code until the next break will be executed if $row['Funcionario'] is that value.

IF with multiple conditions not working

I am trying to create an if statement with multiple conditions but it won't work and perhaps it is my syntax.
I have two post variables, which both give me the value fine elsewhere on my page. They are:
$_POST['text']
$_POST['rating'] //can be G, PG or R
What I am trying to do is make my word filter code work only if the rating equals "G"
What is currently happening though is that the filter is flagging a bad word regardless of the rating and ignoring my IF rating = G part.
if (isset($_POST['text']) and $_POST['rating'] = "G") {
//give warning if bad words are used
}
<?php
if (isset($_POST['text']) && $_POST['rating'] =="G") {
//give warning if bad words are used
}?>
use it like this
You may also use the symbol version of the syntax.
&& for and
|| for or
Also, = does not mean equals in an if statement. That is the syntax for setting a variable.
You would say == (equals to).
To say "not equals" you would use != or !=
if (isset($_POST['text']) && $_POST['rating'] == "G") {
//give warning if bad words are used
}

PHP what that line means? [duplicate]

This question already has answers here:
Reference Guide: What does this symbol mean in PHP? (PHP Syntax)
(24 answers)
Closed 9 years ago.
I am starter php developer, I know, if else, or, elseif... but I don't understand those : ? and other symbols. So can you tell me what this lines mean:
$success = $success ? $b->save(false) : $success;
if (!success) // shouldn't this be without "!"
$transaction->commit(); // this means "do the job, if ok"
else
$transaction->rollBack(); // this means "don't do the job, if not ok"
Also, can you tell me how to call this symbols, I don't know their name and so I can't find tutorials about them
It's pretty common in a lot of languages, you can find this Ternary Operations for example in javascript aswell
It is a short hand for an if/else.
The part before the ? is the condition, the next part is the code to execute if the condition returns true, and the last part (after the :) if it returns false:
condition ? if true : if false;
$a = 3 > 5 ? 'three is greater than five' : 'three is lesser than five';
In this case $a would be three is lesser than five;
I would recommend ternary operations only for very simple conditions/results, if not, you end up writting less maintainable code, sacrificing shortness for legibility
the above code looks like if $success from previous transactions was true , try $b->save(false) and then put the returned value from $b->save(false) into $success.
$b->save(false) means save without validation, and after successful save, will return true
then the if part is very clear
That's a Ternary Operator, a short form for an if statement.
$success = $success ? $b->save(false) : $success;
is the same as
if($success) {
$success = $b->save(false);
} else {
$success = $success;
}

Why does the switch statement execute a case block even when a match is not found?

switch(1){
case 1: print 1; // prints 1 (as expected)
case 2: print 2; // prints 2 (even though match is not equal?)
case 3: print 3; // prints 3 (even though match is not equal?)
}
I know that most programming languages continue to execute each statement if you don't use break after each case expression match. But I'm confused as to why most languages execute a case block as a successful match on this second and third case statement.
Just to clarify:
I am aware of the behavior of the switch statement, but I don't understand the logic that it makes sense to execute a case block/statement as a successful match even though a match is not found.
UPDATE: I just updated the question to reflect most programming languages and not just PHP.
From the manual:
The switch statement executes line by line (actually, statement by statement). In the beginning, no code is executed. Only when a case statement is found with a value that matches the value of the switch expression does PHP begin to execute the statements. PHP continues to execute the statements until the end of the switch block, or the first time it sees a break statement. If you don't write a break statement at the end of a case's statement list, PHP will go on executing the statements of the following case.
switch(1){
case 1:
echo 1; // echos 1 (as expected)
break; // stop!!!
case 2:
echo 2; // won't get here
break;
case 3:
echo 3; //or here
break;
}
The reason it's that way is probably because PHP borrowed the syntax from C.
However the reason it was originally this way is it helps to reduce code duplication I suspect.
If you have an if like:
if($item == 'SOUP' || $item == 'FRIES'){
eat($item);
}elseif($item == 'JUICE'){
drink($item);
}else{
use($item);
}
If switches never followed through you would need 4 cases with 'SOUP' and 'FRIES' having the same logic, without this you can make the switch nicer:
switch($item){
case 'SOUP':
case 'FRIES':
eat($item);
break;
case 'JUICE':
drink($item);
break;
default:
use($item);
break;
}
I know that PHP continues to check the switch statement cases if you don't use break after each case
Seems like you didn't understand. You missed to use the break keyword:
switch(1){
case 1: echo 1; break;
case 2: echo 2; break;
case 3: echo 3; break;
}
Note that a case statement is like an entry point in the code. After a case condition matches the code will run through all cases until the break is reached.
To your update: Note that this behaviour is the same for PHP as for most programming languages including : C, C++, Java, Javascript, ActionScript, Pascal, ....
Why does the switch statement execute a case block even when a match
is not found?
If you do not use break, it will execute all the switches, which can be helpful sometimes. for example:
switch ( count ) {
default : puts ( " ++++.....+++ " ) ;
case 4: puts ( " ++++ " ) ;
case 3: puts ( " +++ " ) ;
case 2: puts ( " ++ " ) ;
case 1: puts ( " + " ) ;
case 0:;
}
So if count is 3 you get output:
+++
++
+
If 2, you get output
++
+
if 10, you get:
++++.....+++
++++
+++
++
+
So there are times when you want your switch to execute the other cases, once it finds what you want. Like the code above.
You could do this with else if, but it would be a lot more typing.

Categories