If else condition in array - php

Hello i am trying to add if else statement in array().
here is my code
$excelData = array(
$users->name,
$users->first_name . ' ' . $organization->last_name,
$users->user_email,
date('d M y', $timestamp),
if ($users->amount == NULL) {echo 0;} else { $users->amount; } ,
if($users->coupon_code == NUll) { echo "No Coupon Code";}else {$users->coupon_code;} ,
);

If/else structures are not meant to be used in-line like that. They don't produce a value, but rather they perform an operation. What you're looking to do is have a single expression which produces a value. The ternary conditional operator can be used for that. (Scroll down on that link to the section titled "Ternary Operator".)
For example, this expression produces a value:
$users->amount == NULL ? 0 : $users->amount
It will evaluate to either 0 or $users->amount based on the condition. So in your code you would have:
$excelData = array(
$users->name,
$users->first_name . ' ' . $organization->last_name,
$users->user_email,
date('d M y', $timestamp),
$users->amount == NULL ? 0 : $users->amount,
$users->coupon_code == NULL ? "No Coupon Code" : $users->coupon_code
);

Related

PHP: Displaying zero to the correct output

I am new to PHP and I am struggling to see why my code is not working when the echo displays 0. The code works for everything else however whenever the random operator chooses 0 it outputs 0 Negative, when I have it to display as Zero. I have no idea why it is doing this and I would appreciate any guidance.
$randomNumber = rand(-5, 5);
$var = $randomNumber;
echo $randomNumber;
echo $integerValue = (($var === 0) ? " Zero" : ($var <=-1) ? " Negative" : (($var >=1) ? " Positive" : " Not Positive or Zero") );
The problem is due to PHP ternary operator precedence, which works backwards compared to most other languages:
Understanding nested PHP ternary operator
Try this last line:
echo $integerValue = (($var === 0) ? " Zero" : (($var <=-1)
? " Negative" : (($var >=1)
? " Positive" : " Not Positive or Zero") ));
You are missing a parentheses:
<?php
$randomNumber = rand(-5, 5);
$var = $randomNumber;
echo $randomNumber;
echo $integerValue = (($var === 0) ? " Zero" : (($var <=-1) ? " Negative" : (($var >=1) ? " Positive" : " Not Positive or Zero") ) );
Explanation:
(
($var === 0) ? " Zero" : (
($var <=-1) ? " Negative" : (
($var >=1) ? " Positive" : " Not Positive or Zero"
)
)
)
You don't want to echo the assignment. You need to assign the value, then echo it. Try changing the last line to
$integerValue = (($var === 0) ? " Zero" : ($var <=-1) ? " Negative" : (($var >=1) ? " Positive" : " Not Positive or Zero") );
and then adding the line
echo $integerValue;
You already have another answer that explains why you weren't getting the outcome you expected, but just FYI, your multiple ternary expression can be simplified somewhat.
echo $var ? $var > 0 ? ' Positive' : ' Negative' : ' Zero';
$var will evaluate to false if it is zero so there's no need to explicitly compare it to zero, and the final "Not Positive or Zero" isn't really a possible outcome, as the result of rand will be an integer, which is either positive, negative, or zero by definition.
Parentheses aren't necessary, but they may make it more obvious what the expression is doing.
echo $var ? ($var > 0 ? ' Positive' : ' Negative') : ' Zero';

PHP Different shorthand if

After checking some shorthand if's i got confused.
$num = 10;
return ($num>0)? 'banned' : 'free';
and
$num = 10;
return ($num>0 ? 'banned' : 'free');
are both equal or the first one is wrong?
Both of the case are true is their own state.
The first one
return ($num>0)? 'banned' : 'free';
is used when you need to compare two or more conditions as in
return ($num > 0 && $num <= 10) ? 'banned' : 'free'. ' model' ;
Here, ' model' is applied to only false condition.
This can be applied into the second expression as well.
The brackets in second expression defined as one expression. as in
return ($num > 0 ? 'banned' : 'free' ) . ' model' ;
Here, ' model' is concatenated to any of the result.
Its totally based on your priority of selecting the bracketss.

if statement not being respected in PHP

if ($fromcat == "true" || $fromcat == 1){
error_log("binding to CAT " . $cat . " because pfc was " . $fromcat);
} else {
error_log("binding to ROOM " . $room . " because pfc was " . $fromcat);
}
please have a look at the code above.
I think everybody agree that if $fromcat is 0 there's no way I could get a "binding to CAT (...)" message in my console.
And yet, here it is:
[01-Apr-2013 22:34:50] binding to CAT single because pfc was 0
How is that even possible? You can't display the word CAT and the number 0 at the same time! Is PHP drunk?
Use the identical (===) comparison operator.
if ($fromcat === "true" || $fromcat === 1) {
error_log("binding to CAT " . $cat . " because pfc was " . $fromcat);
} else {
error_log("binding to ROOM " . $room . " because pfc was " . $fromcat);
}
You are attempting to compare $fromcat to the string "true". If you wanted to compare it to the boolean true, you would use $fromcat == true. Otherwise:
If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically.
Documentation
It's also a good idea to reverse the order of your condition.
So
if ($fromcat === "true" || $fromcat === 1)
becomes
if ('true' === $fromcat || 1 === $fromcat)
Reason: PHP - reversed order in if statement

Ambiguious Ternary Statements

Working on a simple project, the objective is to find whether or not it is a leap year. In PHP, I attempted to use a ternary rather then the standard elseif statements.
$year = 2000;
$is_leapYear = ($year%400 == 0)? true: ($year%100 == 0)? false: ($year % 4 == 0);
echo ($year % 400 == 0) .'.'. ($year % 100 == 0) .'.'. ($year % 4 ==0);
echo $year . ' is ' . ($is_leapYear ? '' : 'not') . ' a leap year';
I discovered that this doesn't work because of a lack of parenthesis. Here is the correct solution:
$is_leapYear = ($year % 400 == 0)? true: (($year % 100 == 0)? false: ($year%4 == 0));
My question is why do ternary operators need parenthesis on the top true or false branch? I don't think the above code is ambiguous.
There's no need for such complicated code. PHP's date() can return whether it's a leap year or not:
$is_leap_year = (bool) date('L', mktime(0, 0, 0, 1, 1, $year));
See manual here.
There is no ambiguity and sadness of PHP Ternary Operator:
<?php
// on first glance, the following appears to output 'true'
echo (true?'true':false?'t':'f');
// however, the actual output of the above is 't'
// this is because ternary expressions are evaluated from left to right
// the following is a more obvious version of the same code as above
echo ((true ? 'true' : false) ? 't' : 'f');
// here, you can see that the first expression is evaluated to 'true', which
// in turn evaluates to (bool)true, thus returning the true branch of the
// second ternary expression.
?>
SOURCE
Your code executes like this:
$year = 2000;
$is_leapYear = (($year%400 == 0)? true: ($year%100 == 0)) ? false: ($year%4==0);
echo $is_leapYear;
LEFT-to-RIGHT

PHP Elseif Ternary Operators

I am trying to convert the following code into a Ternary Operator, but it is not working and I am unsure why. I think my problem is that I do not know how to express the elseif operation in ternary format. From my understanding and elseif is performed the same way as an if operation by using the format : (condition) ? 'result'.
if ($i == 0) {
$top = '<div class="active item">';
} elseif ($i % 5 == 0) {
$top = '<div class="item">';
} else {
$top = '';
}
$top = ($i == 0) ? '<div class="active item">' : ($i % 5 == 0) ? '<div class="item">' : '';
$top = ($i == 0) ? '<div class="active item">' : (($i % 5 == 0) ? '<div class="item">' : '');
you need to add parenthesis' around the entire else block
The Ternary Operator doesn't support a true if... else if... else... operation; however, you can simulate the behavior by using the following technique
var name = (variable === 1) ? 'foo' : ((variable === 2) ? 'bar' : 'baz');
I personally don't care for this as I don't find it more readable or elegant. I typically prefer the switch statement.
switch (variable) {
case 1 : name = 'foo'; break;
case 2 : name = 'bar'; break;
default : name = 'bas'; break;
}
Too late probably to share some views, but nevertheless :)
Use if - else if - else for a limited number of evaluations. Personally I prefer to use if - else if - else when number of comparisons are less than 5.
Use switch-case where number of evaluations are more. Personally I prefer switch-case where cases are more than 5.
Use ternary where a single comparison is under consideration (or a single comparison when looping), or when a if-else compare is needed inside the "case" clause of a switch structure.
Using ternary is faster when comparing while looping over a very large data set.
IMHO Its finally the developer who decides the trade off equation between code readability and performance and that in turn decides what out of, ternary vs. if else-if else vs. switch-case, can be used in any particular situation.
//Use this format before reducing the expression to one liner
$var=4; //Change value to test
echo "Format result: ";
echo($var === 1) ? 'one' : //if NB.=> $varname = || echo || print || var_dump(ternary statement inside); can only be (placed at the start/wrapping) of the statement.
(($var === 2) ? 'two' : //elseif
(($var === 3) ? 'three' : //elseif
(($var === 4) ? 'four' : //elseif
'false' //else
))); //extra tip: closing brackets = totalnumber of conditions - 1
// Then echo($var === 1)?'one':(($var === 2)?'two':(($var === 3)?'three':(($var === 4)?'four':'false')));
echo "<br/>";
var_dump("Short result: ", ($var === 1)?'one':(($var === 2)?'two':(($var === 3)?'three':(($var === 4)?'four':'false'))) );

Categories