Check if an object is null (Shortest way) - php

I try to check if an object is null.
In Groovy I can check:
System.out.println(object?.object2?.property)
In other words
if(object != null){
if(object.object2 != null){
System.out.println(object.object2.property);
}
}
Now I want the same in PHP
How can I write the same in the shortest way?
object->object2->property
object2 can be null
if I try to get the property of object2 I get a NPE
Thanks for help.

in version 8 of PHP you can use Nullsafe operator as follow:
$prop = object?->object2?->property;

you can do:
if( ! $object)
if($object !== null)
If you're using PHP7 you can also do null coalesce operator
$object1 ?? $object2
in your case
if($object && $object->object2)

You can use the isset function over the entire object
if (isset($object->object2->property))
echo 'It exists!';
else
echo 'It does not exist!';

Hi We have a function is_null() or isset()
if(isset(object, object->object2)){
echo(object.object2.property);
}

Related

difficulty to understand a PHP syntax

Suppose we have this method in a class :
public static function example($s, $f = false)
{
(static::$i['s'] === null or $f) and static::$i['s'] = $s;
return new static;
}
would you please give me any hint what is the meaning of this line of code?
(static::$i['s'] === null or $f) and static::$i['s'] = $s;
is it a conditional statement? or something like a ternary operator?
Thanks
They are trying to be clever by using the short circuiting that happens when dealing with logical operators like this. This is what they are doing:
if ((static::$info['syntax'] === null) || $force) {
static::$info['syntax'] = $syntax;
}
If you want to see how this short circuiting works with the &&/and operator:
$a = 'something';
false && $a = 'else';
echo $a;
// output: something
Since the first part is false, it never even runs the statement on the other side since this logical operation already evaluates to false.

PHP - Is there a way to get a variable value if it is set?

I always find myself writing something like:
if(isset($var))
{
DoSomethingWith($var);
}
else
{
DoSomethingWith(null);
}
or
if(isset($arr["key"]))
{
DoSomethingWith($arr["key"];
}
else
{
DoSomethingWith(null);
}
My question is exacly this:
Is there a way to write a get_var_if_set() function so that you can simply write...
DoSomethingWith(get_var_if_set($var));
/// and
DoSomethingWith(get_var_if_set($arr["key"]));
....WITHOUT notifying if $var doesn't exists or that $arr doesn't have a set value for "key"?
I guess it should be something like this:
function get_var_if_set($a)
{
return (isset($a) ? $a : null);
}
But that doesn't work because calling get_var_if_set() with unset variables will always generate a Notice, so it might need a little magic.
Thanks all folks.
Edit
A user who deleted his answer suggested to pass variables by reference, as PHP will pass null if the $variable doesn't exist.
So that would be perfect, take a look at these solutions (which might probably be equivalent):
function get_var_if_set(&$a) { return (isset($a) ? $a : null); }
function get_var_if_set(&$a) { return $a ?? null; } // Only in PHP 7.0+ (Coalescing operator)
Note: Coalescing operator suggested by Koray Küpe
The problem as you can see is that they initialize the passed variables somehow in the return statement.
We don't want that.
If you use PHP 7.0+ you can use null coalescing operator.
return $a ?? null;
Note: The operator checkes whether the variable exist and not empty. So, if the variable is already set but empty, it will return the null variable already.
The problem is not the var itself, but the key of the array key in this:
DoSomethingWith(get_var_if_set($arr["key"]))
So the only solution is to check for the array and the key you're looking for.
function get_var_if_set($a, $key = null)
{
if(is_array($a) && array_key_exists($key, $array)) {
return $a[$key];
} else {
return (isset($a) ? $a : null);
}
}

php: write isset function which returns value or null

I have the following code in numerous places (thousands of places) around my project:
$foo = isset($mixed) ? $mixed : null;
Where $mixed can be anything: array, array element, object, object property, scalar, etc. For example:
$foo = isset($array['element']) ? $array['element'] : null;
$foo = isset($nestedArray['element']['key']) ? $nestedArray['element']['key'] : null;
$foo = isset($object->prop) ? $object->prop : null;
$foo = isset($object->chain->of->props) ? $object->chain->of->props : null;
Is there a way to write this repeated logic as a (simple) function? For example, I tried:
function myIsset($mixed)
{
return isset($mixed) ? $mixed : null;
}
The above function looks like it would work, but it does not in practice. For example, if $object->prop does not exist, and I call myIsset($object->prop)), then I get fatal error: Undefined property: Object::$prop before the function has even been called.
Any ideas on how I would write such a function? Is it even possible?
I realize some solutions were posted here and here, but those solutions are for arrays only.
PHP 7 has a new "Null coalescing operator" which does exactly this. It is a double ?? such as:
$foo = $mixed ?? null;
See http://php.net/manual/en/migration70.new-features.php
I stumbled across the answer to my own question while reading about php references. My solution is as follows:
function issetValueNull(&$mixed)
{
return (isset($mixed)) ? $mixed : null;
}
Calls to this function now look like:
$foo = issetValueNull($array['element']);
$foo = issetValueNull($nestedArray['element']['key']);
$foo = issetValueNull($object->prop);
$foo = issetValueNull($object->chain->of->props);
Hopefully this helps anyone out there looking for a similar solution.
isset is a language construct, not a regular function. Therefore, it can take what would otherwise cause an error, and just return false.
When you call myIsset($object->prop)), the evaluation occurs and you get the error.
See http://php.net/manual/en/function.isset.php
This is the same problem as using typeof nonExistentVariable in JavaScript. typeof is a language construct and will not cause an error.
However, if you try to create a function, you get an error for trying to use an undefined variable.
function isDef(val) {
return typeof val !== 'undefined';
}
console.log( typeof nonExistent !== 'undefined'); // This is OK, returns false
isDef(nonExistent); // Error nonExistent is not defined
You could actually just write it like:
$foo = $mixed?:null;
If you just want to check if it exist do this
function myIsset($mixed)
{
return isset($mixed); // this is a boolean so it will return true or false
}
function f(&$v)
{
$r = null;
if (isset($v)) {
$r = $v;
}
return $r;
}

boolean equivalent to NULL in PHP

is this the right syntax to check if a value is equivalent to NULL or not in PHP:
if($AppointmentNo==NULL)
?
I have tried it but it seems that it is not working. Any suggestion for another syntax?
Thanks
Use is_null():
if(is_null($AppointmentNo)) {
// do stuff
}
Alternatively, you could also use strict comparison (===):
if($AppointmentNo === NULL) {
An example:
$foo = NULL;
if(is_null($foo)) {
echo 'NULL';
} else {
echo 'NOT NULL';
}
Output:
NULL
There is a function called is_null.
is_null($AppointmentNo)
Use is_null().
if (is_null($AppointmentNo))
Typically you would use is_null().
if (is_null($AppountmentNo))

Coalesce function for PHP?

Many programming languages have a coalesce function (returns the first non-NULL value, example). PHP, sadly in 2009, does not.
What would be a good way to implement one in PHP until PHP itself gets a coalesce function?
There is a new operator in php 5.3 which does this: ?:
// A
echo 'A' ?: 'B';
// B
echo '' ?: 'B';
// B
echo false ?: 'B';
// B
echo null ?: 'B';
Source: http://www.php.net/ChangeLog-5.php#5.3.0
PHP 7 introduced a real coalesce operator:
echo $_GET['doesNotExist'] ?? 'fallback'; // prints 'fallback'
If the value before the ?? does not exists or is null the value after the ?? is taken.
The improvement over the mentioned ?: operator is, that the ?? also handles undefined variables without throwing an E_NOTICE.
First hit for "php coalesce" on google.
function coalesce() {
$args = func_get_args();
foreach ($args as $arg) {
if (!empty($arg)) {
return $arg;
}
}
return NULL;
}
http://drupial.com/content/php-coalesce
I really like the ?: operator. Unfortunately, it is not yet implemented on my production environment. So I use the equivalent of this:
function coalesce() {
return array_shift(array_filter(func_get_args()));
}
It is worth noting that due to PHP's treatment of uninitalised variables and array indices, any kind of coalesce function is of limited use. I would love to be able to do this:
$id = coalesce($_GET['id'], $_SESSION['id'], null);
But this will, in most cases, cause PHP to error with an E_NOTICE. The only safe way to test the existence of a variable before using it is to use it directly in empty() or isset(). The ternary operator suggested by Kevin is the best option if you know that all the options in your coalesce are known to be initialised.
Make sure you identify exactly how you want this function to work with certain types. PHP has a wide variety of type-checking or similar functions, so make sure you know how they work. This is an example comparison of is_null() and empty()
$testData = array(
'FALSE' => FALSE
,'0' => 0
,'"0"' => "0"
,'NULL' => NULL
,'array()'=> array()
,'new stdClass()' => new stdClass()
,'$undef' => $undef
);
foreach ( $testData as $key => $var )
{
echo "$key " . (( empty( $var ) ) ? 'is' : 'is not') . " empty<br>";
echo "$key " . (( is_null( $var ) ) ? 'is' : 'is not') . " null<br>";
echo '<hr>';
}
As you can see, empty() returns true for all of these, but is_null() only does so for 2 of them.
I'm expanding on the answer posted by Ethan Kent. That answer will discard non-null arguments that evaluate to false due to the inner workings of array_filter, which isn't what a coalesce function typically does. For example:
echo 42 === coalesce(null, 0, 42) ? 'Oops' : 'Hooray';
Oops
To overcome this, a second argument and function definition are required. The callable function is responsible for telling array_filter whether or not to add the current array value to the result array:
// "callable"
function not_null($i){
return !is_null($i); // strictly non-null, 'isset' possibly not as much
}
function coalesce(){
// pass callable to array_filter
return array_shift(array_filter(func_get_args(), 'not_null'));
}
It would be nice if you could simply pass isset or 'isset' as the 2nd argument to array_filter, but no such luck.
I'm currently using this, but I wonder if it couldn't be improved with some of the new features in PHP 5.
function coalesce() {
$args = func_get_args();
foreach ($args as $arg) {
if (!empty($arg)) {
return $arg;
}
}
return $args[0];
}
PHP 5.3+, with closures:
function coalesce()
{
return array_shift(array_filter(func_get_args(), function ($value) {
return !is_null($value);
}));
}
Demo: https://eval.in/187365
A function to return the first non-NULL value:
function coalesce(&...$args) { // ... as of PHP 5.6
foreach ($args as $arg) {
if (isset($arg)) return $arg;
}
}
Equivalent to $var1 ?? $var2 ?? null in PHP 7+.
A function to return the first non-empty value:
function coalesce(&...$args) {
foreach ($args as $arg) {
if (!empty($arg)) return $arg;
}
}
Equivalent to (isset($var1) ? $var1 : null) ?: (isset($var2) ? $var2 : null) ?: null in PHP 5.3+.
The above will consider a numerical string of "0.00" as non-empty. Typically coming from a HTTP GET, HTTP POST, browser cookie or the MySQL driver passing a float or decimal as numerical string.
A function to return the first variable that is not undefined, null, (bool)false, (int)0, (float)0.00, (string)"", (string)"0", (string)"0.00", (array)[]:
function coalesce(&...$args) {
foreach ($args as $arg) {
if (!empty($arg) && (!is_numeric($arg) || (float)$arg!= 0)) return $arg;
}
}
To be used like:
$myvar = coalesce($var1, $var2, $var3, ...);

Categories