Pawan Choudhary
Pawan Choudhary

Reputation: 1083

PHP function to check if a variable exist or not outside of a function

I am in need of a PHP function to check that a variable exist or not outside of function. If it does not exist, then assign a default value to it.

The function will be something like: function if_exist($argument, $default = '') where $argument will be any variable outside the function. It can be a variable's variable, and $default will be the default value of the variable if the variable doesn't exist.

Please avoid using global scope in the function, because I heard that it's not good for a site's security.

Upvotes: 2

Views: 2563

Answers (5)

SteAp
SteAp

Reputation: 11999

Use this:

function setGlobalIfNotSet( $variableName, $defaultValue = false ) {

  if ( ! isset( $variableName )) {

    global $$variableName;

    $$variableName = $defaultValue;

  }

}

Upvotes: 0

Andrew Moore
Andrew Moore

Reputation: 95474

There are two ways of going at this. You may be looking for the first non-null value or if the actual variable is set or not...

The first use-case is easy... To get the value of the first variable that isn't null, define a function as such:

function coalesce() {
  $args = func_get_args();

  if(is_array($args))
    return null;

  foreach($args as $arg) {
    if($arg !== null)
      return $arg;
  }

  return null;
}

Using this function is easy. Simply call coalesce() with a number of different arguments and it will always return the first non-null value it encounters.

$myVar = coalesce($myVar, null, 'Hello There', 'World');
echo $myVar; // Hello there

However, if you are looking for a function to check if a variable is defined, and if it isn't define it, then you need to create a function which forces the first argument to be a reference.

function set_default(&$variable, $defaultValue = null) {
  if(!isset($variable)) {
    $variable = $defaultValue;

    return false;
  }
  return true;
}

Upvotes: 0

Ribose
Ribose

Reputation: 2233

You can make a function to use isset:

function isset_default($v, $default = '') {
    return isset($v) ? $v : $default;
}

Usage:

$v = isset_default($v, 'somedefaultvalue');

Upvotes: -1

phant0m
phant0m

Reputation: 16905

I don't see why you want a function for this at all.

$a = isset($a) ? $a : "my default string";

Everybody will understand what your code does without resorting to little-known "features" of PHP and having to look at your functions body to see what it does.

Even though it may look like a function call, it's not. isset() is a language construct! That's why it will not raise a Notice.

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 817208

You can make $argument pass-by-reference:

function if_exist(&$argument, $default="") {
   if(!isset($argument)) {
       $argument = $default;
       return false;
   }
   return true;
}

DEMO

Upvotes: 5

Related Questions