Various PHP Tips, Tricks, and Gotchas: Parameter Order, String Operators, OpCache, Security, Reflection, and More
This article compiles a wide range of practical PHP knowledge—including function‑parameter ordering, proper salt storage, newline handling, string‑operator precedence, http_build_query quirks, OpCache basics, the HTTPOXY vulnerability, operator precedence nuances, instanceof behavior, array_map tricks, performance considerations for array functions, type‑juggling pitfalls, comparison changes in PHP 8, and different ways to merge arrays—providing code examples and references for each topic.
When browsing the PHP documentation the author collected many interesting and sometimes confusing details, documenting them with explanations and code examples.
Parameter order
Array functions expect parameters in the order needle, haystack, while string functions use haystack, needle.
Array function parameters are ordered as "needle, haystack"
String functions are the opposite, "haystack, needle".Storing salts
When using password_hash() or crypt(), the returned hash already contains the salt, so you can store the full hash in the database and verify with password_verify() or crypt().
Newline handling in ?>
PHP treats the closing tag ?> and ?>\n the same; to force a line break you must add an extra newline after the closing tag.
String concatenation operator precedence
When concatenating strings with . and performing arithmetic, the operators have the same precedence and are evaluated left‑to‑right, which can lead to unexpected results such as "Result: " . $var + 3 producing a warning and the value 3. Use parentheses to enforce the intended order.
<?php
$var = 3;
echo "Result: " . $var + 3; // warning, result 3
?> <?php
$var = 3;
echo "Result: " . ($var + 3); // correct output
?>String concatenation with numbers
Using . with numbers converts them to strings, e.g., 1 . 2 yields "12", while 1 + 2 yields 3.
http_build_query behavior
Null values are omitted, booleans are cast to 1 and 0, and empty arrays disappear from the query string.
OpCache principle
PHP code goes through scanning, parsing, compilation to opcodes, and execution. Opcache (or APC) caches the compiled opcodes, skipping the first three steps on subsequent requests and dramatically improving performance.
Why var_dump(1...9) prints 10.9
The tokeniser treats 1. as a float, . as the concatenation operator, and .9 as another float, which are then concatenated into the string "10.9" before being evaluated.
HTTPOXY vulnerability
In CGI mode, HTTP headers are prefixed with HTTP_ and become environment variables. An attacker can set a Proxy header, causing HTTP_PROXY to be controllable and potentially hijack outbound requests. Mitigation includes clearing fastcgi_param HTTP_PROXY "" in Nginx or checking php_sapi_name() before trusting the variable.
fastcgi_param HTTP_PROXY "";Operator precedence pitfalls
The assignment operator = has higher precedence than and, so $bool = true and false assigns true to $bool before evaluating and false. Use && or parentheses to avoid this.
<?php
$bool = true && false; // false
var_dump($bool);
$bool = true and false; // true
var_dump($bool);
?>instanceof and negation
The instanceof operator has higher precedence than !, so ! $obj instanceof Class is parsed as !($obj instanceof Class). In complex expressions add parentheses for clarity.
Interesting array_map usages
Besides simple mapping, array_map can accept multiple arrays; the callback receives corresponding elements from each array, and shorter arrays are padded with null.
<?php
$arr1 = ['apple','orange','mango','pear'];
$arr2 = ['cauliflower','lettuce','kale','romaine'];
function map1($a,$b){ var_dump($a,$b); }
array_map('map1',$arr1,$arr2);
?>Performance of array functions
Functions like array_unique and array_merge can be slower than a simple foreach loop, especially when misused. Understanding their Big‑O complexities helps write efficient code.
Type‑juggling pitfalls
Strings that start with 0e are interpreted as scientific notation, making md5('240610708') and md5('QNKCDZO') compare equal with ==. Use strict comparison === for security‑critical checks.
<?php
$a = md5('240610708'); // 0e462097...
$b = md5('QNKCDZO'); // 0e830400...
var_dump($a == $b); // true (bad)
var_dump($a === $b); // false (good)
?>Disabling unsafe functions
Functions like eval cannot be disabled via disable_functions because they are language constructs, not regular functions. To block them you need extensions or custom code.
Casting to null
Using (unset)$var (deprecated) or settype($var, 'null') can force a variable to become null.
isset and unset with multiple arguments
Both functions accept several variables; isset returns true only if all arguments are set and not null.
Quick reference lookup
PHP manual pages can be accessed directly via https://php.net/<keyword>, e.g., https://php.net/isset.
Reflection to call protected/private methods
Reflection allows invoking non‑public methods and accessing properties, as well as instantiating objects without calling their constructors.
<?php
class Lisa { public function name(){return 'Lisa';} protected function age(){return 22;} private function weight(){return 95;}}
$rc = new ReflectionClass('Lisa');
$age = $rc->getMethod('age');
$age->setAccessible(true);
var_dump($age->invoke($rc->newInstance())); // 22
?>Instantiating without constructor
<?php
class Dog { private $name; public function __construct($name){$this->name=$name;}}
$rc = new ReflectionClass('Dog');
$dog = $rc->newInstanceWithoutConstructor();
var_dump($dog->getName()); // null
?>Getting parent classes
<?php
class A{}
class B extends A{}
class C extends B{}
class D extends C{}
var_dump(class_parents('D'));
?>Increment/Decrement quirks
Incrementing false does nothing, but += 1 works. Incrementing null yields 1, while decrementing leaves it null. Letters can be incremented (e.g., 'z'++ => 'aa') but not decremented.
Comparison changes in PHP 8
Non‑strict comparison between numbers and non‑numeric strings now converts the number to a string first, making 0 == "foo" evaluate to false (previously true).
Array comparison
Using == checks for value equality regardless of order or types, while === also checks key order and types.
Merging arrays
array_merge()appends values and reindexes numeric keys; the + operator (union) keeps the first array’s values for duplicate keys and preserves numeric keys.
$a = [1,2,3];
$b = [2,3,4];
var_dump(array_merge($a,$b)); // [1,2,3,2,3,4]
var_dump($a + $b); // [1,2,3]The article ends with a disclaimer that most content is collected from the web, invites corrections, and provides links to the original sources.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
