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');
Tschallacka
  • 27,901
  • 14
  • 88
  • 133
green
  • 23
  • 5
  • PHP has three functions that should help you: `isset()`, `empty()` and `is_null()`. You should read the PHP doc for more info. – xander Mar 08 '18 at 09:22
  • Do you mean you want your `init_variable` function to gracefully handle the case when `$_POST['ABC']` is not defined? – deceze Mar 08 '18 at 09:23
  • yes, i want to handle the case when it is not defined. – green Mar 08 '18 at 09:24
  • Find all you need in [this post](https://stackoverflow.com/questions/4261133/php-notice-undefined-variable-notice-undefined-index-and-notice-undef) – Clerenz Mar 08 '18 at 09: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`. – CD001 Mar 08 '18 at 09:37

5 Answers5

6

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

$variable1 = $_POST['ABC'] ?? 'DEFAULT VALUE'
OzzyCzech
  • 9,713
  • 3
  • 50
  • 34
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'];
ArtisticPhoenix
  • 21,464
  • 2
  • 24
  • 38
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';
deceze
  • 510,633
  • 85
  • 743
  • 889
  • 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. – green Mar 08 '18 at 11:25
  • 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. – deceze Mar 08 '18 at 11:29
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');
Tschallacka
  • 27,901
  • 14
  • 88
  • 133
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
Rick James
  • 135,179
  • 13
  • 127
  • 222