1

I want to write a function to set an undefined variable to the default value that it can prevent warning of an undefined variable.

If I use the isset() function to determine the input variable, the variable will change to the default value if a variable is equal to NULL. Could any method implement this?

Example:

function init_variable($input, $default = '123'){
    ...
    return $inited_variable;
}

$variable1 = init_variable($_POST['ABC']);
$variable2 = init_variable($_POST['DEF'], 'DEF');
5
  • PHP has three functions that should help you: isset(), empty() and is_null(). You should read the PHP doc for more info. Commented Mar 8, 2018 at 9:22
  • Do you mean you want your init_variable function to gracefully handle the case when $_POST['ABC'] is not defined? Commented Mar 8, 2018 at 9:23
  • yes, i want to handle the case when it is not defined. Commented Mar 8, 2018 at 9:24
  • Find all you need in this post Commented Mar 8, 2018 at 9:24
  • note: is_null() will return true on a variable that hasn't been defined; there isn't a default type for variables - but undefined variables are null. Commented Mar 8, 2018 at 9:37

5 Answers 5

6

There is a much more elegant way since PHP 7 called Null coalescing operator:

$variable1 = $_POST['ABC'] ?? 'DEFAULT VALUE'
Sign up to request clarification or add additional context in comments.

Comments

1

If you just want to set defaults:

PHP < v7 (ternary)

$var = isset($_POST['ABC'])) ? $_POST['ABC'] : false;

PHP >= v7 (null coalesce)

$var = $_POST['ABC'] ?? false;

Any (roughly equivalent)

$var = false;

if(isset($_POST['ABC'])) $var = $_POST['ABC'];

Comments

0

If $_POST['ABC'] does not exist, then PHP will raise an error at exactly this point:

init_variable($_POST['ABC'])

You cannot prevent this error from happening from within init_variable. Your function will only receive the end result of trying to access an undefined variable/index, it cannot prevent that from happening.

What you want is simply the null coalescing operator:

$variable1 = $_POST['ABC'] ?? '123';

Or perhaps:

$variable2 = isset($_POST['ABC']) ? $_POST['ABC'] : '123';

2 Comments

if the checking isset($_POST['ABC']) ? $_POST['ABC'] : '123'; in function is doing at the first time, it is workable too as i teseted. however, the function cannot determine between NULL and undefined.
You can determine whether an array_key_exists specifically, which allows you to distinguish between undefined and null. But there is indeed no way to distinguish between an undefined variable and a variable holding null. Specifically for $_POST: POSTed data can never be null, at worst it's an empty string, so that shouldn't really be any concern.
0

You could include this in your project

https://github.com/rappasoft/laravel-helpers/blob/master/src/helpers.php

or use this variety

if ( ! function_exists('array_get'))
{
    /**
     * Get an item from an array using "dot" notation.
     *
     * @param  array   $array
     * @param  string  $key
     * @param  mixed   $default
     * @return mixed
     */
    function array_get($array, $key, $default = null)
    {
        if (is_null($key)) return $array;
        if (isset($array[$key])) return $array[$key];
        foreach (explode('.', $key) as $segment)
        {
            if ( ! is_array($array) || ! array_key_exists($segment, $array))
            {
                return $default;
            }
            $array = $array[$segment];
        }
        return $array;
    }
}

What it does is split the string by dot (.) and then try to fetch the elmenents that in that array. so if you'd do array_get($array, 'foo'); it would be as if you'd type $array['foo']. But if the variable is set in the array, it will return it's value. null is a valid value, but not one you're likely to find in a $_POST array.

But if you also wish to filter out the null values I do recommend using a manual check instead of a catch all. Sometimes you want that null. But if you need a function for it I suggest modifying the above function to

if ( ! function_exists('array_get'))
{
    /**
     * Get an item from an array using "dot" notation.
     *
     * @param  array   $array
     * @param  string  $key
     * @param  mixed   $default
     * @return mixed
     */
    function array_get($array, $key, $default = null)
    {
        if (is_null($key)) return $array;
        if (isset($array[$key])) {
            $value = $array[$key];
            /**
             * Here is the null check. You can also add empty checks and other checks.
             */
            if(is_null($value)) {
               return $default;
            }
            return $value
        }
        foreach (explode('.', $key) as $segment)
        {
            if ( ! is_array($array) || ! array_key_exists($segment, $array))
            {
                return $default;
            }
            $array = $array[$segment];
        }
        return $array;
    }
}

Then you can simply use

array_get($_POST,'abc','some default value');

That way you don't have to worry if it's intantiated or not.

Added bonus is, if you have nested arrays, this makes it easy to access them without having to worry if the lower arrays are initiated or not.

$arr = ['foo' => ['bar' => ['baz' => 'Hello world']]];

array_get($arr, 'foo.bar.baz', 'The world has ended');
array_get($arr, 'foo.bar.ouch', 'The world has ended');

Comments

0

I use:

$x = @$_POST['x'];

Often I want more than just a default value, so I do one of:

if ($x) { ... }          // if it can be treated like a boolean
if (! empty($x)) { ... } // for cases where empty string, but not NULL, is possible
if (isset($x)){ ... }    // just checks for presence

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.