there is this function called Nz() in visual basic for application. the function checks variable nullity and returns a provided value if it finds the variable is null.
i try to write the same function in php, which looks like below:
function replace_null($value, $replace) {
if (!isset($value)) {
return $replace;
} else {
return $value;
}
}
$address = replace_null($data['address'], 'Address is not available.');
of course, if $data['address'] is found null, php will stop executing the code and replace_null won't be called.
i'm currently using ternary
(isset(data['address']) ? data['address'] : 'Address is not available.');
but i think replace_null, if it works, will offer a more convenient way.
is there a function in php that provide the same functionality as vba's Nz()?
any suggestion will be appreciated.
thanks in advance.
A bit roundabout: If you only use this to check for array members, you could pass the key separately:
function get_with_default($arr, $key, $defval)
{
return isset($arr[$key]) ? $arr[$key] : $defval;
}
If the variable could be set but null (Edit: which it cannot, thanks #deceze), add another check:
function get_and_coalesce_with_default($arr, $key, $defval)
{
return (isset($arr[$key]) && !is_null($arr[$key]) ? $arr[$key] : $defval;
}
As pointed out, isset() only succeeds on non-null values, so the above doesn't add anything. We can write a non-trivial check with array_key_exists, though:
function get_with_default_v2($arr, $key, $defval)
{
return (array_key_exists($key, $arr) && !is_null($arr[$key]) ? $arr[$key] : $defval;
}
You could pass the array and the key separately like this:
function valueOrDefault($array, $key, $default) {
return isset($array[$key]) ? $array[$key] : $default;
}
$address = valueOrDefault($data, 'address', 'Address is not available.');
If you pass by reference, PHP won't error out:
function Nz(&$var, $def='') {
return isset($var) ? $var : $def;
}
http://php.net/manual/en/language.references.pass.php
If the variable is declared you do something like $value?:$replace
function replace_null($value='', $replace='') {
if (!isset($value)) {
return $replace;
} else {
return $value;
}
}
Try this. It will allow you to call the function with or without passing parameters.
<?
function replace_null($value, $replace) {
if(empty($value) && $value !== '0') {
return $replace;
} else {
return $value;
}
}
$address = replace_null("0", "replacing null");
echo $address;
?>
I think using the is_null function would be much more useful:
$address = $data['address'];
if ( is_null($address) ) $address = 'Address is not available.';
If you really want this as a function:
function replace_null($value, $replace) {
if (is_null($value)) return $replace;
return $value;
}
$address = replace_null($data['address'], 'Address is not available.');
Related
i would like to create a php function. Basically, that's what i've :
if(isset($myvariable) AND $myvariable == "something")
{
echo 'You can continue';
}
and that's what i want :
if(IssetCond($myvariable, "something"))
{
echo 'You can continue';
}
I want function that tests if the variable exists, and if it does it tests if the condition is respected. Otherwise it returns false.
I've tried a lot of things, but i still have a problem when $myvariable doesnt exist.
function IssetCond($var, $value){
if(isset($var) AND $var == $value)
{
return true;
}
else
{
return false;
}
}
When $myvariable exists and whether the condition is respected or not, it works.
If you have some minutes to help me i'll be grateful.
Thanks
Thomas
You can pass just the name, not the var, and use variable variable
function IssetCond($var, $value){
return (isset($$var) AND $var == $value);
}
Used like
if(IssetCond('myvariable', "something"))
{
echo 'You can continue';
}
Your idea it good but if you pass a variable to your function you pass the value of that variable to your function. If your variable is not set before you get an error that you try to prevent with your function.
You could pass the reference to the function but that would cause the same problem if you variable is not set before.
I think i found the answer, thanks to #Teko
$a = "3";
function IssetCond($var, $value){
global $$var;
if (isset($$var) && $$var == $value)
{ return true;}
return false;
}
if(IssetCond('d', 4))
{
echo 'first test'; // wont display
}
if(IssetCond("a", 3))
{
echo 'second test'; // will display
}
if(IssetCond("a", 4))
{
echo 'third test'; // wont display
}
Thanks to everyone !
function valueFromGetOrPost($parameter)
{
$shvalue=NULL;
if ($_GET[$parameter])
{
$shvalue=$_GET[$parameter];
}
else if (isset($_POST[$parameter]))
{
$shvalue=$_POST[$parameter];
}
return $shvalue;
}
say by using filter_input
Basically the code check whether a parameter exist either in GET or POST. And then return the value of the parameter.
I think this must be so common it should be there by some built in function already
Use $_REQUEST (documentation).
An associative array that by default contains the contents of $_GET, $_POST and $_COOKIE.
So your code will look like:
function valueFromGetOrPost($parameter)
{
$shvalue=NULL;
if ($_REQUEST[$parameter])
{
$shvalue=$_REQUEST[$parameter];
}
return $shvalue;
}
You could use fast return to simplify it a bit, i.e
function valueFromGetOrPost($parameter){
$shvalue=NULL;
if (isset($_GET[$parameter])){
return $_GET[$parameter];
} else if (isset($_POST[$parameter])){
return $_POST[$parameter];
}
}
Or, you could use a ternary operator, since you're returning NULL anyway if neither are set:
function valueFromGetOrPost($parameter){
$shvalue = (isset($_GET[$parameter]) ? $_GET[$parameter] : $_POST[$parameter]);
return $shvalue;
}
Here is my proposal, using the filter_input() function:
function valueFromGetOrPost($parameter)
{
$value = ($getValue = filter_input(INPUT_GET, $parameter))
? $getValue
: filter_input(INPUT_POST, $parameter);
return ($value) ? $value : NULL;
}
I have the following function to check the array's keys
public function check($arr, $key, $default = NULL) {
return isset($arr[$key]) && !empty($arr[$key]) ? $arr[$key] : $default;
}
$this->check($info, 'location'); //it's working
$this->check($info['birthday'], 'year'); //it's working
$this->check($_POST, 'email'); //it's working
$this->check($_POST, 'password'); //it's working
everything is ok until multidimensional array appears
Notice: Array to string conversion in
change your function code to:
public function check($arr, $key, $default = NULL) {
return isset($arr[$key]) ? $arr[$key] : $default;
}
if you still want to check for empty value (though isset is enough):
public function check($arr, $key, $default = NULL) {
return isset($arr[$key]) && (!empty($arr[$key]) || is_array($arr[$key])) ? $arr[$key] : $default;
}
Not 100% sure what are you looking for but please notice that if you have email[][] field, when you return $arr[$key] you are returning an array. So you have to check if $arr[$key] is an array before returning its value.
public function check($arr, $key, $default = NULL) {
if( isset($arr[$key]) && !empty($arr[$key]) || is_array($arr[$key])) {
if(is_array($arr[$key])) {
//apply here your second level check condition
} else return $arr[$key]; // returns its value (if it's not an array)
} else return $default;
}
Hope it helps
Instead, if you're trying to build a function checking recursively if $key is contained somewhere in a multidimensional array, you have to do otherwise (that's why I wrote I'm not 100% sure what you're looking for)
? $arr[$key]
In the above code you are using $_POST['email'] (which is an array) as a string.
How to exclude a variable from being required in a function?
IE:
function foo($name,$address,$pizza_preference,$date)
{
if(!$pizza_preference)
{
return array($name,$address,$date);
}
else
{
return array($name,$address,$pizza_preference,$date);
}
}
When calling this function how would I set it up so $pizza_preference is not required, but optional? So that if you only entered 3 arguments in the function it omits $pizza_preference, or would I have to make it so when you enter 0 it just doesn't return it?
Just define a default value for it. Then you can use that function without passing a value:
function foo($name,$address,$date,$pizza_preference=null)
{
if(!$pizza_preference)
{
return array($name,$address,$date);
}
else
{
return array($name,$address,$pizza_preference,$date);
}
}
Usually you put variables that have default values at the end of the parameters list so you don't have to include blank parameters when calling the function.
See Default argument values on the PHP website for more.
UPDATE
If you're going to have multiple parameters with default values and want to be able to skip them individually you can pass an array as the only parameter and read the values from there:
function foo(array $parameters)
{
if(!$parameters['pizza_preference'])
{
return array($parameters['name'],$parameters['address'],$parameters['date']);
}
else
{
return array($parameters['name'],$parameters['address'],$parameters['date'],$parameters['pizza_preference']);
}
}
I recommend (and I always do) to pass arguments as Object..
function foo($params)
{
if(!$params->pizza_preference)
{
return array($pizza_preference->name,$pizza_preference->address,$pizza_preference->date);
}
else
{
return array($pizza_preference->name,$pizza_preference->pizza_preference->address,$pizza_preference,$pizza_preference->date);
}
}
Sample usage:
$p1 = new stdClass;
$p1->name = 'same name';
$p1->address ='same address';
$p1->pizza_preference = '1';
$p1->date = '26-04-2012';
$p2 = new stdClass;
$p2->name = 'same name';
$p2->address ='same address';
$p2->date = '26-04-2012';
foo($p1); //will return the first array
foo($p2); //will return the second array
Well youll need to change the signature... anything not required should go last:
function foo($name, $address, $date, $pizza_preference = null) {
}
You can set default values in the function declaration:
function foo($name,$address,$date,$pizza_preference=null)
{
if($pizza_preference === null)
{
return array($name,$address,$date);
}
else
{
return array($name,$address,$pizza_preference,$date);
}
}
As an alternative approach, you can use an associative array as a single argument, and then just check it inside the function like this:
function foo($args) {
$name = (!empty($args['name']) ? $args['name'] : NULL);
$address = (!empty($args['address']) ? $args['address'] : NULL);
$pizza_preference = (!empty($args['pizza_preference']) ? $args['pizza_preference'] : NULL);
$date = (!empty($args['date']) ? $args['date'] : NULL);
}
I'm coding a worksheet app for a printer company.
I'm getting flood of forms.
For every single input field I have to check if the $_POST variables are set, and if, so echo back the value. (In case of some error, for example after a validation error, the user shouldn't retype the whole form)
Sample code:
if(isset($_POST['time'])&&!empty($_POST['time'])){echo $_POST['time'];}
I had to implement this about a hundred times.
So I tried to figure out some kind of function to make this simple and readable.
Something like this:
function if_post_echo($key, $default = "") {
if(isset($_POST[$key])&&!empty($_POST[$key])){
echo $_POST[$key];
}else{
echo $default;
}
}
But this wont work.
I have tried to pass in the $_POST for the $key variable like this:
if_post_echo($_POST['time'])
function if_request_echo($key, $default = "") {
if(isset($key)&&!empty($key)){
echo $key;
}else{
echo $default;
}
}
And I also tried this:
function if_request_echo($key, $default = null) {
return isset($_REQUEST[$key])&&!empty($_REQUEST[$key]) ? $_REQUEST[$key] : $default;
}
Without any reasonable outcome.
The question:
How can I forge a function that looks for the necessary $_POST variable and returns it or if its unset then returns an empty string.
And is there a way to do this for $_GET and $_REQUEST, too? (Or simply duplicate?)
Your PHP testing function:
<?php
function test_req($key, $default = '') {
if(isset($_REQUEST[$key]) and
!empty($_REQUEST[$key])) {
return $_REQUEST[$key];
} else {
return $default;
}
}
?>
Then in your form HTML:
<input name="my_field" value="<?php echo htmlentities(test_req('my_field')); ?>" />
$_REQUEST (linked) is a PHP super global that contains both POST ($_POST) and GET ($_GET) request parameters.
If you only want to capture POST request parameters then it would be:
<?php
function test_req($key, $default = '') {
if(isset($_POST[$key]) and
!empty($_POST[$key])) {
return $_POST[$key];
} else {
return $default;
}
}
?>
For example.
If you have a large amount of fields, I would propose that you also use an array of defaults:
$defaults = array(
"time" => "default",
"name" => "enter name here",
"text..." => "...",
);
$fields = array_filter($_POST) + $defaults;
$fields will then contain a list of form values with either the POST data or a preset default. No isset, see?
array_filter man page particularly: If no callback is supplied, all entries of input equal to FALSE will be removed. Goes some way to explaining the working behind this solution.
This should work:
function if_post_echo($key, $default = ''){
if(isset($_POST[$key]) AND !empty($_POST[$key]){
echo $_POST[$key];
}
echo $default;
}
If you're having problems I recommend that you try var_dump($_POST) or print_r($_POST) to see if everything has been properly posted.
Just to note, this is redundant:
isset($_POST[$key]) && !empty($_POST[$key])
An unset variable is going to always be "empty", so isset() is implied in your empty() call.
For your logic you can achieve the same result with just:
!empty($_POST[$key])
Your first function works perfectly to me.
Why do you think it doesn't work?
However, a better variant would be
function _post($key, $default = "") {
if(isset($_POST[$key])){
return $_POST[$key];
}else{
return $default;
}
}
To use it :
echo $_post($key); // You could define the message as a second parameter.
function requireArray( $array, $required ) {
foreach( $required as $k=>$v ) {
if ( !isset($array[$k]) || empty($array[$k]) )
return false;
}
return true;
}
#call like this:
requireArray($_POST, array('time', 'username', 'foo'));
If you want to know specifically:
function missingFrom( $array, $required ) {
$r = array();
foreach( $required as $k ) {
if ( !isset($array[$k]) || empty($array[$k]) )
$r[] = $k;
}
return $r;
}
Called like previous function.
Your method seems to work fine here:
function if_post_echo($key, $default = "") {
if(isset($_POST[$key])&&!empty($_POST[$key])){
echo $_POST[$key];
}else{
echo $default;
}
}
I made a simple input with the name test and the form method is POST and using echo if_post_echo('test');.
It posted on the page what was in the text box.
This feature is being added in PHP 7 as the "Null Coalesce Operator" using two question marks:
echo ($_GET['message'] ?? 'default-if-not-set');
https://wiki.php.net/rfc/isset_ternary