use functions in php-isset with ternary operator - php

Simple stuff,
This works without any problems:
$openMonday = rtrim(chunk_split($result['opening_hours']['periods'][1]['open']['time'], 2, ':'), ':');
$business->openingTimes['monday'] = isset($openMonday) ? $result['opening_hours']['periods'][1]['open']['time'] : '';
But I don't want to write two lines for this because then I would have to do it also for all the other opening hours.
Why can't I just write
$business->openingTimes['monday'] = isset(rtrim(chunk_split($result['opening_hours']['periods'][1]['open']['time'], 2, ':'), ':')) ? $result['opening_hours']['periods'][1]['open']['time'] : '';
I'm always getting the error that it's expecting a variable. How can I use methods in the isset with ternary operator?

The problem here is that isset() is not a real function but a language construct, which requires its arguments to be variables, or it issues a syntax error.
See also the manual entry: http://php.net/manual/en/function.isset.php
Anyway, as also #deceze said, you probably do not want to use isset() here, since it is used to check if a variable exists.
In this case, you could use empty(), so instead of writing
$openMonday = rtrim(chunk_split($result['opening_hours']['periods'][1]['open']['time'], 2, ':'), ':');
$business->openingTimes['monday'] = isset($openMonday) ? $result['opening_hours']['periods'][1]['open']['time'] : '';
you could do
$openMonday = rtrim(chunk_split($result['opening_hours']['periods'][1]['open']['time'], 2, ':'), ':');
$business->openingTimes['monday'] = !empty($openMonday) ? $result['opening_hours']['periods'][1]['open']['time'] : '';
And you should not worry to make it a one-liner at any cost! Create a function instead, and then call it when needed... But if you really still want to do it inline, then you could do
$business->openingTimes['monday'] = !empty(rtrim(chunk_split($result['opening_hours']['periods'][1]['open']['time'], 2, ':'), ':')) ? $result['opening_hours']['periods'][1]['open']['time'] : '';
just remember that the above requires at least PHP 5.5!
And finally, the row above could just be written as
$business->openingTimes['monday'] = !rtrim(chunk_split($result['opening_hours']['periods'][1]['open']['time'], 2, ':'), ':') ? $result['opening_hours']['periods'][1]['open']['time'] : '';
without any need for isset() nor empty()

You don't need isset here! isset is used to safely test whether... well... a variable exists. You know your variable exists, because you're declaring it on the line before. If you want to mush it into one line, you're not even using a variable, you're directly working with the value. You just want to compare the value to false, which you can do inline easily.
Just get rid of isset. And read The Definitive Guide To PHP's isset And empty.

SOLUTION
$business->openingTimes['monday'] = isset($result['opening_hours']['periods'][1]['open']['time']) ? rtrim(chunk_split($result['opening_hours']['periods'][1]['open']['time'], 2, ':'), ':') : '';
To explain what I did. I asked if the variable is set, and if so it uses the method chunk_split otherwise the string will be empty.

Related

Message: Trying to get property of non-object error in php [duplicate]

Is there in PHP something similar to JavaScript's:
alert(test || 'Hello');
So, when test is undefined or null we'll see Hello, otherwise - we'll see the value of test.
I tried similar syntax in PHP but it doesn't seem to be working right... Also I've got no idea how to google this problem..
thanks
Edit
I should probably add that I wanted to use it inside an array:
$arr = array($one || 'one?', $two || 'two?'); //This is wrong
But indeed, I can use the inline '? :' if statement here as well, thanks.
$arr = array(is_null($one) ? "one?" : $one, is_null($two) ? "two ?" : $two); //OK
you can do echo $test ?: 'hello';
This will echo $test if it is true and 'hello' otherwise.
Note it will throw a notice or strict error if $test is not set but...
This shouldn't be a problem since most servers are set to ignore these errors. Most frameworks have code that triggers these errors.
Edit: This is a classic Ternary Operator, but with the middle part left out. Available since PHP 5.3.
echo $test ? $test : 'hello'; // this is the same
echo $test ?: 'hello'; // as this one
This only checks for the truthiness of the first variable and not if it is undefined, in which case it triggers the E_NOTICE error. For the latter, check the PHP7 answer below (soon hopefully above).
From PHP 7 onwards you can use something called a coalesce operator which does exactly what you want without the E_NOTICE that ?: triggers.
To use it you use ?? which will check if the value on the left is set and not null.
$arr = array($one ?? 'one?', $two ?? 'two?');
See #Yamiko's answer below for a PHP7 solution https://stackoverflow.com/a/29217577/140413
echo (!$test) ? 'hello' : $test;
Or you can be a little more robust and do this
echo isset($test) ? $test : 'hello';
As per the latest version use this for the shorthand
$var = $value ?? "secondvalue";
One-liner. Super readable, works for regular variables, arrays and objects.
// standard variable string
$result = #$var_str ?: "default";
// missing array element
$result = #$var_arr["missing"] ?: "default";
// missing object member
$result = #$var_obj->missing ?: "default";
See it in action: Php Sandbox Demo
I'm very surprised this isn't suggested in the other answers:
echo isset($test) ? $test : 'hello';
From the docs isset($var) will return false if $var doesn't exist or is set to null.
The null coalesce operator from PHP 7 onwards, described by #Yamiko, is a syntax shortcut for the above.
In this case:
echo $test ?? 'hello';
If you want to create an array this way, array_map provides a more concise way to do this (depending on the number of elements in the array):
function defined_map($value, $default) {
return (!isset($value) || is_null($value)) ? $default : $value;
// or return $value ? $default : $value;
}
$values = array($one, $two);
$defaults = array('one', 'two');
$values = array_map('defined_map', $values, $defaults);
Just make sure you know which elements evaluate to false so you can apply the right test.
Since php7.4, you can use the null coalescing assignment, so that you can do
$arr = array($one ??= "one?", $two ??= "two ?");
See the docs here
There may be a better way, but this is the first thing that came to my mind:
echo (!$test) ? "Hello" : $test;
Null is false in PHP, therefore you can use ternary:
alert($test ? $test : 'Hello');
Edit:
This also holds for an empty string, since ternary uses the '===' equality rather than '=='
And empty or null string is false whether using the '===' or '==' operator. I really should test my answers first.
Well, expanding that notation you supplied means you come up with:
if (test) {
alert(test);
} else {
alert('Hello');
}
So it's just a simple if...else construct. In PHP, you can shorten simple if...else constructs as something called a 'ternary expression':
alert($test ? $test : 'Hello');
Obviously there is no equivalent to the JS alert function in PHP, but the construct is the same.
alert((test == null || test == undefined)?'hello':test);
I recently had the very same problem.This is how i solved it:
<?php if (empty($row['test'])) {
echo "Not Provided";}
else {
echo $row['test'];}?></h5></span></span>
</div>
Your value in the database is in variable $test..so if $test row is empty then echo Not Provided

Assign if variable is set

In PHP I find myself writing code like this frequently:
$a = isset($the->very->long->variable[$index])
? $the->very->long->variable[$index]
: null;
Is there a simpler way to do this? Preferably one that doesn't require me to write $the->very->long->variable[$index] twice.
An update, because PHP 7 is now out and is a game-changer on this point ; the previous answers are about PHP 5.
PHP 7 solves this issue. Because you are true at saying that it is frequent to write this in PHP, and that's absolutely not elegant.
In PHP 7 comes the Null Coalesce Operator (RFC), which is a perfect shorthand for the isset ternary condition.
Its goal is to replace this type of condition:
$var = isset($dict['optional']) ? $dict['optional'] : 'fallback';
By that:
$var = $dict['optional'] ?? 'fallback';
Even better, the null coalesce operators are chainable:
$x = null;
# $y = null; (undefined)
$z = 'fallback';
# PHP 7
echo $x ?? $y ?? $z #=> "fallback"
# PHP 5
echo isset($x) ? $x : (isset($y) ? $y : $z)
The null coalesce operator acts exactly like isset() : the subject variable's value is taken if:
The variable is defined (it exists)
The variable is not null
Just a note for PHP beginners: if you use the ternary condition but you know that the subject variable is necessarily defined (but you want a fallback for falsy values), there's the Elvis operator:
$var = $dict['optional'] ?: 'fallback';
With the Elvis operator, if $dict['optional'] is an invalid offset or $dict is undefined, you'll get a E_NOTICE warning (PHP 5 & 7). That's why, in PHP 5, people are using the hideous isset a ? a : b form when they're not sure about the input.
Sadly no, because the RFC has been declined. And because isset is not a function but a language construct you cannot write your own function for this case.
Note: Because this is a language construct and not a function, it cannot be called using variable functions.
If you only assign null instead of the non set variable, you can use:
$a = #$the->very->long->variable[$index];
# makes that instruction throw no errors
Assuming you know that $the->very->long->variable is set, and you're just worried about the array index....
$x = $the->very->long->variable;
$a = isset($x[$index]) ? $x[$index] : null;
Or for a more generic variant that you can use around you code:
function array_valifset($arr,$k, $default=null) {
return isset($arr[$k]) ? $arr[$k] : $default;
}
then call it like this for any array value:
$a = array_valifset($the->very->long->variable,$index);
I stumbled across the same problem and discovered that referencing an array element does not issue a notice or warning but returns null (at least PHP 5.6).
$foo = ['bar' => 1];
var_dump($bar = &$foo['bar']); // int 1
var_dump($baz = &$foo['baz']); // null
Inside an if statement:
if($bar = &$foo['bar']) {
echo $bar;
}
if($baz = &$foo['baz']) {
echo $baz;
}

Passing safe parameters to function or letting function check it?

Please consider code below
<?php
$a = '';
echo empty($a) ? '' : substr($a, 0, 1); // Prints: ''
echo substr($a, 0, 1); // Prints: ''
Which "echo" is better? In first one always $a will be checked and substr will run normally and in second one, substr checks $a internally and may trigger some notice errors.
The first one is better.
You always need to prevent errors / warnings / notices.
Although I wouldn't even use the one-liner just for readability.
The input string must be one character or longer. So it is better to check before.
Please check : http://php.net/manual/en/function.substr.php
The most important part is that you differ between input and output variables:
$input['a'] = '';
$output['a'] = empty($input['a']) ? '' : substr($input['a'], 0, 1);
echo $output['a'];
How you write the validation is your business, it should deal with all edge cases and should not trigger any errors/warnings.
Edit: If you're concerned to reduce the number of function calls, the following snippet does not make use of any functions, only one language constructs:
$a = empty($a[0])?'':$a[0];
echo $a;

PHP best way to check whether a string is empty or not

I've seen a lot of php code that does the following to check whether a string is valid by doing:
$str is a string variable.
if (!isset($str) || $str !== '') {
// do something
}
I prefer to just do
if (strlen($str) > 0) {
// something
}
Is there any thing that can go wrong with the second method? Are there any casting issues I should be aware of?
Since PHP will treat a string containing a zero ('0') as empty, it makes the empty() function an unsuitable solution.
Instead, test that the variable is explicitly not equal to an empty string:
$stringvar !== ''
As the OP and Gras Double and others have shown, the variable should also be checked for initialization to avoid a warning or error (depending on settings):
isset($stringvar)
This results in the more acceptable:
if (isset($stringvar) && $stringvar !== '') {
}
PHP has a lot of bad conventions. I originally answered this (over 9 years ago) using the empty() function, as seen below. I've long since abandoned PHP, but since this answer attracts downvotes and comments every few years, I've updated it. Should the OP wish to change the accepted answer, please do so.
Original Answer:
if(empty($stringvar))
{
// do something
}
You could also add trim() to eliminate whitespace if that is to be considered.
Edit:
Note that for a string like '0', this will return true, while strlen() will not.
You need isset() in case $str is possibly undefined:
if (isset($str) && $str !== '') {
// variable set, not empty string
}
Using !empty() would have an important caveat: the string '0' evaluates to false.
Also, sometimes one wants to check, in addition, that $str is not something falsy, like false or null[1]. The previous code doesn't handle this. It's one of the rare situations where loose comparison may be useful:
if (isset($str) && $str != '') {
// variable set, not empty string, not falsy
}
The above method is interesting as it remains concise and doesn't filter out '0'. But make sure to document your code if you use it.
Otherwise you can use this equivalent but more verbose version:
if (isset($str) && (string) $str !== '') {
// variable set, not empty string, not falsy
}
Of course, if you are sure $str is defined, you can omit the isset($str) from the above codes.
Finally, considering that '' == false, '0' == false, but '' != '0', you may have guessed it: PHP comparisons aren't transitive (fun graphs included).
[1] Note that isset() already filters out null.
This will safely check for a string containing only whitespace:
// Determines if the supplied string is an empty string.
// Empty is defined as null or containing only whitespace.
// '0' is NOT an empty string!
function isEmptyString($str) {
return !(isset($str) && (strlen(trim($str)) > 0));
}
What about this:
if( !isset($str[0]) )
echo "str is NULL or an empty string";
I found it on PHP manual in a comment by Antone Roundy
I posted it here, because I did some tests and it seems to work well, but I'm wondering if there is some side effect I'm not considering. Any suggestions in comments here would be appreciated.
According to PHP empty() doc (http://ca1.php.net/empty):
Prior to PHP 5.5, empty() only supports variables; anything else will result in a parse error. In other words, the following will not work: empty(trim($name)). Instead, use trim($name) == false.
This simple old question is still tricky.
strlen($var) works perfectly ONLY if you're absolutely sure the $var is a string.
isset($var) and empty($var) result are based on type of the variable, and could be tricky at some cases (like empty string ""). View the table in this page for more details.
UPDATE
There are actually 2 cases for this question:
Case 1: You're sure that your variable is always going to be a "string":
In this case, just test the length:
if(strlen($str) > 0) {
// do something..
}
Case 2: Your variable may and may not be a "string":
In this case, it depends on what you want to do. For me (most of the time), if it's not a string then I validate it as "false". You can do it this way:
if(is_string($var) && $var !== '') {// true only if it's a string AND is not empty
// do something ...
}
And to make it shorter and in 1 condition instead of 2 (specially useful if you're testing more than 1 string in same if condition), I made it into function:
function isNonEmptyString($var) {
return is_string($var) && $var !== '';
}
// Somewhere else..
// Reducing conditions to half
if(isNonEmptyString($var1) && isNonEmptyString($var2) && isNonEmptyString($var3)) {
// do something
}
If your variable $str is not defined then your strlen() method will throw an exception. That is the whole purpose of using isset() first.
trimming the string will also help if there are string with white spaces.
if (isset($str) && trim($str) !== '') {
// code
}
I think not, because strlen (string lenght) returns the lenght (integer) of your $str variable.
So if the variable is empty i would return 0. Is 0 greater then 0. Don't think so.
But i think the first method might be a little more safer. Because it checks if the variable is init, and if its not empty.

Setting default values (conditional assignment)

In Ruby you can easily set a default value for a variable
x ||= "default"
The above statement will set the value of x to "default" if x is nil or false
Is there a similar shortcut in PHP or do I have to use the longer form:
$x = (isset($x))? $x : "default";
Are there any easier ways to handle this in PHP?
As of PHP 5.3 you can use the ternary operator while omitting the middle argument:
$x = $x ?: 'default';
As of PHP 7.0, you can also use the null coalesce operator
// PHP version < 7.0, using a standard ternary
$x = (isset($_GET['y'])) ? $_GET['y'] : 'not set';
// PHP version >= 7.0
$x = $_GET['y'] ?? 'not set';
isset($x) or $x = 'default';
As of PHP 7.4 you can write:
$x ??= "default";
This works as long as $x is null. Other "falsy" values don't count as "not set".
I wrap it in a function:
function default($value, $default) {
return $value ? $value : $default;
}
// then use it like:
$x=default($x, 'default');
Some people may not like it, but it keeps your code cleaner if you're doing a crazy function call.
I think your longer form is already the shortcut for php... and I wouldn't use it, because it is not good to read
Some notice:
In the symfony framework most of the "get"-Methods have a second parameter to define a default value...

Categories