"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP



PHP Snippet 1:

$o = [];
@$var = ["",0,null,1,2,3,$foo,$o['myIndex']];
array_walk($var, function($v) {
    echo (!isset($v) || $v == false) ? 'true ' : 'false';
    echo ' ' . (empty($v) ? 'true' : 'false');
    echo "\n";
});

PHP Snippet 2:

//Initializing variable
$value = ""; //Initialization value; Examples
             //"" When you want to append stuff later
             //0  When you want to add numbers later
//isset()
$value = isset($_POST['value']) ? $_POST['value'] : '';
//empty()
$value = !empty($_POST['value']) ? $_POST['value'] : '';

PHP Snippet 3:

    // Null coalesce operator - No need to explicitly initialize the variable.
    $value = $_POST['value'] ?? '';

PHP Snippet 4:

set_error_handler('myHandlerForMinorErrors', E_NOTICE | E_STRICT)

PHP Snippet 5:

error_reporting( error_reporting() & ~E_NOTICE )

PHP Snippet 6:

//isset()
$value = isset($array['my_index']) ? $array['my_index'] : '';
//array_key_exists()
$value = array_key_exists('my_index', $array) ? $array['my_index'] : '';

PHP Snippet 7:

list($a, $b) = array(0 => 'a');
//or
list($one, $two) = explode(',', 'test string');

PHP Snippet 8:

// recommended solution for recent PHP versions
$user_name = $_SESSION['user_name'] ?? '';

// pre-7 PHP versions
$user_name = '';
if (!empty($_SESSION['user_name'])) {
     $user_name = $_SESSION['user_name'];
}

PHP Snippet 9:

// not the best solution, but works
// in your php setting use, it helps hiding site wide notices
error_reporting(E_ALL ^ E_NOTICE);

PHP Snippet 10:

$var = @($_GET["optional_param"]);

PHP Snippet 11:

var_dump($_GET);
var_dump($_POST);
//print_r($_REQUEST);

PHP Snippet 12:

print_r($_SERVER);

PHP Snippet 13:

function ifexists($varname)
{
  return(isset($$varname) ? $varname : null);
}

PHP Snippet 14:

<?= ifexists('name') ?>

PHP Snippet 15:

function ifexistsidx($var,$index)
{
  return(isset($var[$index]) ? $var[$index] : null);
}

PHP Snippet 16:

<?= ifexistsidx($_REQUEST, 'name') ?>

PHP Snippet 17:

$a = 10;
if($a == 5) {
    $user_location = 'Paris';
}
else {
}
echo $user_location;

PHP Snippet 18:

$a = 10;
if($a == 5) {
    $user_location='Paris';
}
else {
    $user_location='SOMETHING OR BLANK';
}
echo $user_location;

PHP Snippet 19:

$value = filter_input(INPUT_POST, 'value');

PHP Snippet 20:

if (!isset($_POST['value'])) {
    $value = null;
} elseif (is_array($_POST['value'])) {
    $value = false;
} else {
    $value = $_POST['value'];
}

PHP Snippet 21:

$value = (string)filter_input(INPUT_POST, 'value');

PHP Snippet 22:

$user_location = null;

PHP Snippet 23:

function foo()
{
    $my_variable_name = '';

    //....

    if ($my_variable_name) {
        // perform some logic
    }
}

PHP Snippet 24:

// verbose way - generally better
if (isset($my_array['my_index'])) {
    echo "My index value is: " . $my_array['my_index'];
}

// non-verbose ternary example - I use this sometimes for small rules.
$my_index_val = isset($my_array['my_index'])?$my_array['my_index']:'(undefined)';
echo "My index value is: " . $my_index_val;

PHP Snippet 25:

$my_array = array(
    'my_index' => ''
);

//...

$my_array['my_index'] = 'new string';

PHP Snippet 26:

// Echo whatever the hell this is
<?=$_POST['something']?>

PHP Snippet 27:

// If this is set, echo a filtered version
<?=isset($_POST['something']) ? html($_POST['something']) : ''?>

PHP Snippet 28:

echo "My index value is: " . ($my_array["my_index"] ?? '');

PHP Snippet 29:

echo "My index value is: " . (isset($my_array["my_index"]) ? $my_array["my_index"] : '');

PHP Snippet 30:

$greeting = "Hello, " . exst($user_name, 'Visitor') . " from " . exst($user_location);


/**
 * 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
 */

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;
}

PHP Snippet 31:

<?php
    error_reporting(E_ALL); // Making sure all notices are on

    function idxVal(&$var, $default = null) {
        return empty($var) ? $var = $default : $var;
    }

    echo idxVal($arr['test']);         // Returns null without any notice
    echo idxVal($arr['hey ho'], 'yo'); // Returns yo and assigns it to the array index. Nice
?>

PHP Snippet 32:

<?php
    $newArray[] = {1, 2, 3, 4, 5};
    print_r($newArray[5]);
?>

PHP Snippet 33:

<?php print_r($myvar); ?>

PHP Snippet 34:

php> echo array_key_exists(1, $myarray);

PHP Snippet 35:

$newVariable = isset($thePotentialData) ? $thePotentialData : null;

PHP Snippet 36:

$newVariable = $thePotentialData ?? null;

PHP Snippet 37:

if (isset($thePotentialData)) {
    $newVariable = $thePotentialData;
} else {
    $newVariable = null;
}

PHP Snippet 38:

echo 'Your name is: ' . isset($name) ? $name : 'You did not provide one';

PHP Snippet 39:

$foreName = getForeName(isset($userId) ? $userId : null);

function getForeName($userId)
{
    if ($userId === null) {
        // Etc
    }
}

PHP Snippet 40:

class Person
{
    protected $firstName;
    protected $lastName;

    public function setFullName($first, $last)
    {
        // Correct
        $this->firstName = $first;

        // Incorrect
        $lastName = $last;

        // Incorrect
        $this->$lastName = $last;
    }
}

PHP Snippet 41:

$query = "SELECT col1 FROM table WHERE col_x = ?";

PHP Snippet 42:

print_r($row['col1']);
print_r($row['col2']); // undefined index thrown

PHP Snippet 43:

while( $row = fetching_function($query) ) {

    echo $row['col1'];
    echo "<br>";
    echo $row['col2']; // undefined index thrown
    echo "<br>";
    echo $row['col3']; // undefined index thrown

}

PHP Snippet 44:

<form action="example.php" method="post">
    <p>
        <input type="text" name="name" />
        <input type="submit" value="Submit" />
    </p>
</form>

<select name="choice">
    <option value="choice1">choice 1</option>
    <option value="choice2">choice 2</option>
    <option value="choice3">choice 3</option>
    <option value="choice4">choice 4</option>
</select>

PHP Snippet 45:

<form action="example.php" method="post">
    <select name="choice">
        <option value="choice1">choice 1</option>
        <option value="choice2">choice 2</option>
        <option value="choice3">choice 3</option>
        <option value="choice4">choice 4</option>
    </select>
    <p>
        <input type="text" name="name" />
        <input type="submit" value="Submit" />
    </p>
</form>

PHP Snippet 46:

ini_set('error_reporting', 'on');
ini_set('display_errors', 'on');
error_reporting(E_ALL);

PHP Snippet 47:

if ($my == 9) {
 $test = 'yes';  // Will produce an error as $my is not 9.
}
echo $test;

PHP Snippet 48:

$test = NULL;
if ($my == 9) {
 $test = 'yes';  // Will produce an error as $my is not 9.
}
echo $test;

PHP Snippet 49:

153    foreach($cities as $key => $city){
154        if(($city != 'London') && ($city != 'Madrid') && ($citiesCounterArray[$key] >= 1)){

PHP Snippet 50:

foreach($cities as $key => $city){
    if(array_key_exists($key, $citiesCounterArray)){
        if(($city != 'London') && ($city != 'Madrid') && ($citiesCounterArray[$key] >= 1)){

PHP Snippet 51:

if(isset($_POST['param'])){
    $param = $_POST['param'];
} else {
    # Do something else
}

PHP Snippet 52:

$my_variable_name = "Variable name"; // defining variable
echo "My variable value is: " . $my_variable_name;

if(isset($my_array["my_index"])){
    echo "My index value is: " . $my_array["my_index"]; // check if my_index is set 
}

PHP Snippet 53:

ini_set("error_reporting", false)

PHP Snippet 54:

<!-- The data encoding type, enctype, MUST be specified as below -->
<form enctype="multipart/form-data" action="__URL__" method="POST">
    <!-- MAX_FILE_SIZE must precede the file input field -->
    <input type="hidden" name="MAX_FILE_SIZE" value="30000" />
    <!-- Name of input element determines name in $_FILES array -->
    Send this file: <input name="userfile" type="file" />
    <input type="submit" value="Send File" />
</form>

PHP Snippet 55:

<?php
// In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
// of $_FILES.

$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

echo '<pre>';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
    echo "File is valid, and was successfully uploaded.\n";
} else {
    echo "Possible file upload attack!\n";
}

echo 'Here is some more debugging info:';
print_r($_FILES);

print "</pre>";

?>

PHP Snippet 56:

// If you only want to check variable has value and value has true and false value.
// But variable must be defined first.

if($my_variable_name){

}

// If you want to check if the variable is defined or undefined
// Isset() does not check that variable has a true or false value
// But it checks the null value of a variable
if(isset($my_variable_name)){

}

PHP Snippet 57:

// It will work with: true, false, and NULL
$defineVariable = false;
if($defineVariable){
    echo "true";
}else{
    echo "false";
}

// It will check if the variable is defined or not and if the variable has a null value.
if(isset($unDefineVariable)){
    echo "true";
}else{
    echo "false";
}