I would like to simplify this PHP process that checks if a value is blank.
If the value is blank, the variable gets set to null. If not, the variable is set to the value.
In this case, I have successfully posted a jquery object (called criteria) to PHP for processing. I then set the variables to the values in the object. I use IF/ELSE statements to check if the object value is blank.
<?php
if(isset($_POST['criteria']))
{
$value = $_POST['criteria'];
if($value['recentsq'] == ""){$recentsq = null;}else{$recentsq = $value['recentsq'];}
if($value['custname'] == ""){$custname = null;}else{$custname = $value['custname'];}
if($value['address'] == ""){$address = null;}else{$address = $value['address'];}
}
?>
I have quite a few of these values I need to check and set.
My question is how can I simplify this process by using a custom function?
5条答案
按热度按时间xlpyo6sf1#
You can simply create a method like:
in above method, i am using ternary operator.
In your example, you can just call this method like:
Additional Point for future visitors:
According to PHP manual, If you are using PHP 7:
The null coalescing operator (??) has been added as syntactic sugar for the common case of needing to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.
equal to:
nxowjjhe2#
Or you can use directly the Null coalescing operator from PHP 7
x6h2sr283#
Alternatively, you can use
empty
function:Then you don't even need to have separate
isset
checks.k2fxgqgv4#
Can use the following function get value from array and set a default initial value, by default null
Usage:
Output:
Like @christophe say since php7 can do something like
sg3maiej5#
php function to check if input is blank. its collected from laravel
blank
function