I am trying to add an if-else statement inside of an 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;
},
);
How do I set the default value if the normally accessed value is loosely equal to null?
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
);