Recent Posts

Showing posts with label PHP.. Show all posts
Showing posts with label PHP.. Show all posts

How to solve: Notice: Undefined Index

Happens when you try to access an array by a key that does not exist in the array.
A typical example for an Undefined Index notice would be (demo)
$data = array('foo' => '42', 'bar');
echo $data['spinach'];
echo $data[1];
Both spinach and 1 do not exist in the array, causing an E_NOTICE to be triggered.
The solution is to make sure the index or offset does exist, either by using array_key_exists or isset prior to accessing that index.
$data = array('foo' => '42', 'bar');
if (array_key_exists('spinach', $data)) {
    echo $data['spinach'];
}
else {
    echo 'No key spinach in array';
}

How to solve: Fatal error: Using $this when not in object context

$this is a special variable in PHP which can not be assigned. If it is accessed in a context where it does not exist, this fatal error is given.
This error can occur:
  1. If a non-static method is called statically. Example:
    class Foo {
       protected $var;
       public function __construct($var) {
           $this->var = $var;
       }
    
       public static function bar () {
           // ^^^^^^
           echo $this->var;
           //   ^^^^^
       }
    }
    
    Foo::bar();
    How to fix: review your code again, $this could only used in object context, and should never in a static method. And also, static method should not access the non-static property. Use self::$static_property to access the static property.
  2. If code from a class method has been copied over into a normal function or just the global scopeand keeping the $this special variable.
    How to fix: Review the code and replace $this with a different substitution variable.

How to solve: Parse error: syntax error, unexpected T_XXX

This happens when you have T_XXX token in unexpected place, unbalanced (superfluous) parentheses, use of short tag without activating it in php.ini, and many more.

How to solve: Parse error: syntax error, unexpected '['

This error comes in two variatians:

Variation 1

$arr = [1, 2, 3];
This array initializer syntax was only introduced in PHP 5.4; it will raise a parser error on versions before that. If possible, upgrade your installation or use the old syntax:
$arr = array(1, 2, 3);
See also this example from the manual.

Variation 2

$suffix = explode(',', 'foo,bar')[1];
Array dereferencing function results was also introduced in PHP 5.4. If it's not possible to upgrade you need to use a temporary variable:
$parts = explode(',', 'foo,bar');
$suffix = $parts[1];
See also this example from the manual.