Skip to content

Instantly share code, notes, and snippets.

@bryanwillis
Last active March 8, 2016 09:52
Show Gist options
  • Save bryanwillis/db6d05d5b1083f7d70df to your computer and use it in GitHub Desktop.
Save bryanwillis/db6d05d5b1083f7d70df to your computer and use it in GitHub Desktop.
Awesome function I came across awhile back to fix issues in php when debugging is giving you undefined variables. Whatever is undefined just replace with exst(). For example if variable $xyz is undefined replace it with exst($xyz) and it will not longer return errors. While it's better to write your code in a way to avoid this, it's an easy way …

These check if variable isset or not

function is_set( & $variable ) { if ( isset( $variable ) and ! is_null( $variable ) ) return true; else return false; }

if(!empty($_POST[myField])) { //Do my PHP code }

null

if (isset($var) && ($var === true)) { ... } array_key_exists('v', $GLOBALS)

isset()

isset — Determine if a variable is set and is not NULL

In other words, it returns true only when the variable is not null.

empty()

empty — Determine whether a variable is empty

In other words, it will return true if the variable is an empty string, false, array(), NULL, “0?, 0, and an unset variable.

is_null()

https://www.virendrachandak.com/techtalk/php-isset-vs-empty-vs-is_null/

https://gist.github.com/JeffreyWay/3194444

<?php
// recommended solution
$user_name = $_SESSION['user_name'];
if (empty($user_name)) $user_name = '';
// OR
// just define at the top of the script index.php
$user_name = '';
$user_name = $_SESSION['user_name'];
// OR
$user_name = $_SESSION['user_name'];
if (!isset($user_name)) $user_name = '';
/**
* Function exst() - Checks if the variable has been set
* (copy/paste it in any place of your code)
*
* If the variable is set and not empty returns the variable (no transformation)
* If the variable is not set or empty, returns the $default value
*
* @param mixed $var
* @param mixed $default
*
* @return mixed
*
* Example
* $greeting = "Hello, ".exst($user_name, 'Visitor')." from ".exst($user_location);
*/
function exst( & $var, $default = "")
{
$t = "";
if ( !isset($var) || !$var ) {
if (isset($default) && $default != "") $t = $default;
}
else {
$t = $var;
}
if (is_string($t)) $t = trim($t);
return $t;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment