Especially for web development, PHP is one of the most popular general-purpose scripting language that has been widely used as a framework and especially suitable for use with Web Development.
10 common gotchas in php
Loose Type Comparisons
- Using
==instead of===can lead to unexpected results due to type juggling.
1 2var_dump(0 == 'foo'); // true var_dump(0 === 'foo'); // false- Using
Uninitialized Variables
- Accessing variables before assignment does not throw errors, but returns null.
1echo $x; // null, no errorGlobal Variables in Functions
- Variables are not global inside functions unless declared with
global.
1 2 3 4 5$a = 1; function test() { global $a; echo $a; }- Variables are not global inside functions unless declared with
Array Indexing
- PHP arrays are ordered maps, and mixing numeric and string keys can be confusing.
1 2$arr = [0 => 'a', '1' => 'b', 2 => 'c']; print_r($arr);Magic Quotes and Deprecated Features
- Some older features are deprecated or removed; always check your PHP version.
1 2// magic_quotes_gpc is removed in PHP 5.4+ // Use filter_input() or prepared statements insteadCase Sensitivity
- Variable names are case-sensitive, but function names are not.
1 2 3 4$foo = 1; echo $Foo; // undefined variable function test() { return 1; } echo TEST(); // worksSession Handling
- Forgetting to call
session_start()before using sessions causes issues.
1 2 3// Always call session_start() before accessing $_SESSION session_start(); $_SESSION['user'] = 'admin';- Forgetting to call
Error Reporting Levels
- Not setting error reporting can hide bugs during development.
1 2error_reporting(E_ALL); ini_set('display_errors', 1);Include/Require Paths
- Relative paths can break includes; use absolute paths or
__DIR__.
1include __DIR__ . '/file.php';- Relative paths can break includes; use absolute paths or
Superglobals Scope
- Superglobals like
$_POSTare always available, but may not be populated as expected in CLI scripts.
1 2// $_POST is empty when running from CLI print_r($_POST);- Superglobals like
What should I keep in mind to avoid common pitfalls when working with PHP!