Php hints

The spam filter installed on this site is currently unavailable. Per site policy, we are unable to accept new submissions until that problem is resolved. Please try resubmitting the form in a couple of minutes.

This document was shared by chx in #drupal.hu irc channel. Original was found on github, but unfortunally it's deleted, so I don't know who write it.

I've just saved it for me unpublished, but now, I'm publishing and add some style.
--------------------------------------------------------------------------

This document discusses difficult traps and pitfalls in PHP, and how to avoid, work around, or at least understand them.

If you're brand new to PHP, read [[Articles/PHP Intro]] first.

All of it! PHP is a Terrible Language! LOL!

PHP has more (and more severe) design flaws than most modern languages. Despite this, Facebook has built a 50-billion-dollar enterprise on it.

If this is going to be a problem, you should take some time and really reflect on your career choices.

usort(), uksort(), and uasort() are Slow

This family of functions is extremely slow. You should avoid them if at all possible. Instead, build an array which contains surrogate keys that are naturally sortable with a function that uses native comparison (e.g., sort(), asort(), ksort(), or natcasesort()). Sort this array instead, and use it to reorder the original array.

In our environment, you can often do this easily with array_psort(). You also need to account for i18n and locale-aware collation, which array_psort() will handle for you.

array_intersect() and array_diff() are Also Slow

These functions are much slower for even moderately large inputs than array_intersect_key() and array_diff_key(), because they can not make the assumption that their inputs are unique scalars as the key varieties can. Strongly prefer the key varieties.

array_uintersect() and array_udiff() are Definitely Slow Too

These functions have the problems of both the usort() family and the array_diff() family. Don't use them.

array_merge() in a Loop is Incredibly Slow

If you merge arrays like this:
[geshifilter-php] $result = array(); foreach ($list_of_lists as $one_list) { $result = array_merge($result, $one_list); } [/geshifilter-php]

...your program takes O(N^2) runtime because it generates N intermediate arrays. You should use array_merge_fast(). But be CAREFUL, don't use array_merge_fast() in a loop either! This is equally wrong:

[geshifilter-php] $result = array(); foreach ($list_of_lists as $one_list) { $result = array_merge_fast(array($result, $one_list)); } [/geshifilter-php]
Instead you should do:
[geshifilter-php] $result = array_merge_fast($list_of_lists); // Note that this is not within a loop! [/geshifilter-php]

isset(), empty() and Truthiness

A value is "truthy" if it evaluates to true in an if clause:

[geshifilter-php] $value = something(); if ($value) { // Value is truthy. } [/geshifilter-php]

If a value is not truthy, it is "falsey". These values are falsey in PHP:

[geshifilter-php] null // null 0 // integer 0.0 // float "0" // string "" // empty string false // boolean array() // empty array [/geshifilter-php]

Disregarding some bizarre edge cases, all other values are truthy. Note that because "0" is falsey, this sort of thing (intended to prevent users from making empty comments) is wrong in PHP:

[geshifilter-php] if ($comment_text) { make_comment($comment_text); } [/geshifilter-php]

This is wrong because it prevents users from making the comment "0". THIS COMMENT IS TOTALLY AWESOME AND I MAKE IT ALL THE TIME SO YOU HAD BETTER NOT BREAK IT!!! A better test is probably strlen().

In addition to truth tests with if, PHP has two special truthiness operators which look like functions but aren't: empty() and isset(). These operators help deal with undeclared variables.

In PHP, there are two major cases where you get undeclared variables -- either you directly use a variable without declaring it:
[geshifilter-php] function f() { if ($not_declared) { // ... } } [/geshifilter-php]

...or you index into an array with an index which may not exist:

[geshifilter-php] function f(array $mystery) { if ($mystery['stuff']) { // ... } } [/geshifilter-php]

When you do this, PHP issues a warning. Avoid these warnings by using empty() and isset() to do tests that are safe to apply to undeclared variables.

empty() evaluates truthiness exactly opposite of if(). isset() returns true for everything except null. This is the truth table:

VALUE if() empty() isset()

null false true false

0 false true true

0.0 false true true

"0" false true true

"" false true true

false false true true

array() false true true

EVERYTHING ELSE true false true

The value of these operators is that they accept undeclared variables and do not issue a warning. Specifically, if you try to do this you get a warning:

[geshifilter-php] if ($not_previously_declared) // PHP Notice: Undefined variable! [/geshifilter-php]

But these are fine:

[geshifilter-php] if (empty($not_previously_declared)) // No notice, returns true. if (isset($not_previously_declared)) // No notice, returns false. [/geshifilter-php]

So, isset() really means is_declared_and_is_set_to_something_other_than_null(). empty() really means is_falsey_or_is_not_declared(). Thus:

  • If a variable is known to exist, test falsiness with if (!$v), not empty(). In particular, test for empty arrays with if (!$array). There is no reason to ever use empty() on a declared variable.
  • When you use isset() on an array key, like isset($array['key']), it will evaluate to "false" if the key exists but has the value null! Test for index existence with array_key_exists().

Put another way, use isset() if you want to type "if ($value !== null)" but are testing something that may not be declared. Use empty() if you want to type "if (!$value)" but you are testing something that may not be declared.

foreach() Does Not Create Scope

Variables survive outside of the scope of foreach(). More problematically, references survive outside of the scope of foreach(). This code mutates $array because the reference leaks from the first loop to the second:

[geshifilter-php] $array = range(1, 3); echo implode(',', $array); // Outputs '1,2,3' foreach ($array as &$value) {} echo implode(',', $array); // Outputs '1,2,3' foreach ($array as $value) {} echo implode(',', $array); // Outputs '1,2,2' [/geshifilter-php]

Avoid using foreach-by-reference. If you do opt to use it, unset the reference after the loop:

[geshifilter-php] foreach ($array as &$value) { // ... } unset($value); [/geshifilter-php]

unserialize() is Incredibly Slow on Large Datasets

The performance of unserialize() is nonlinear in the number of zvals you unserialize, roughly O(N^2).

zvalsapproximate time
100005ms
10000085ms
10000008,000ms
1000000072 billion years

var_export() Loves to Kill Babies

If you try to var_export() an object that contains recursive references, your program will terminate. You have no chance to stop this from happening. Avoid var_export() unless you are certain you have only simple data. You can use print_r() or var_dump() to display complex variables.

json_encode() Gives Up Very Easily

PHP's json_encode() completely discards data if it has an invalid UTF-8 subsequence. Use fb_json_encode() (and fb_json_decode()) to avoid these problems.

call_user_func() Breaks References

If you use call_use_func() to invoke a function which takes parameters by reference, the variables you pass in will have their references broken and will emerge unmodified. That is, if you have a function that takes references:

[geshifilter-php] function add_one(&$v) { $v++; } [/geshifilter-php]

...and you call it with call_user_func():

[geshifilter-php] $x = 41; call_user_func('add_one', $x); [/geshifilter-php]

...$x will not be modified. The solution is to use call_user_func_array() and wrap the reference in an array:

[geshifilter-php] $x = 41; call_user_func_array( 'add_one', array(&$x)); // Note '&$x'! [/geshifilter-php]

This will work as expected.

You Can't Throw From __toString()

If you throw from __toString(), your program will terminate uselessly and you won't get the exception.

An Object Can Have Any Scalar as a Property

Object properties are not limited to legal variable names:

[geshifilter-php] $property = '!@#$%^&*()'; $obj->$property = 'zebra'; echo $obj->$property; // Outputs 'zebra'. [/geshifilter-php]

So, don't make assumptions about property names.

There is an (object) Cast

You can cast a dictionary into an object.

[geshifilter-php] $obj = (object)array('flavor' => 'coconut'); echo $obj->flavor; // Outputs 'coconut'. echo get_class($obj); // Outputs 'stdClass'. [/geshifilter-php]

This is occasionally useful, mostly to force an object to become a Javascript dictionary (vs a list) when passed to fb_json_encode().

$arr['42'] refers to the same value as $arr[42]

So:

[geshifilter-php] $arr = array(); $arr[42] = 'spoo'; echo $arr['42']; // outputs "spoo" echo $arr[' 42']; // note leading space; "undefined index"[/geshifilter-php]

Do you really, really want to put an integer-like string key in an array? All is not lost! You can do it with an array cast, but good luck getting that value back.

[geshifilter-php] $obj = new stdClass(); $zero = 0; $obj->$zero = 'blub'; $arr = (array)$obj; var_export($arr); // outputs "array( '0' => 'blub' )". BUT: echo $arr['0']; // undefined index, fool! [/geshifilter-php]

There is a Builtin __PHP_Incomplete_Class Which Answers to No Master

See _warn_incomplete_object().

PHP Leaks Like a Sieve

Everything in PHP leaks a lot of memory. "Everything" does NOT mean "some rare library functions which you can avoid if you are careful", it means "basic array operations" and probably "comments". Do not build long-running PHP services.

Invoking "new" With an Argument Vector is Really Hard

If you have some $className and some $argv of constructor arguments and you want to do this:

[geshifilter-php] new $className($argv[0], $argv[1], ...); [/geshifilter-php]

...you'll probably invent a very interesting, very novel solution that is very wrong. Use newv().

Equality is not Transitive

This isn't terribly surprising since equality isn't transitive in a lot of languages, but the == operator is not transitive:

[geshifilter-php] $a = ''; $b = 0; $c = '0a'; $a == $b; // true $b == $c; // true $c == $a; // false! [/geshifilter-php]

When either operand is an integer, the other operand is cast to an integer before comparison. Avoid this and similar pitfalls by using the === operator, which is transitive.

All 676 Letters in the Alphabet

This doesn't do what you'd expect it to do in C:

[geshifilter-php] for ($c = 'a'; $c <= 'z'; $c++) { // ... } [/geshifilter-php]

This is because the successor to 'z' is 'aa', which is "less than" 'z'. The loop will run for ~700 iterations until it reaches 'zz' and terminates. That is, $c will take on these values:

[geshifilter-php] a b ... y z aa // loop continues because 'aa' <= 'z' ab ... mf mg ... zw zx zy zz // loop now terminates because 'zz' > 'z' [/geshifilter-php]

Instead, use this loop:

[geshifilter-php] foreach (range('a', 'z') as $c) { // ... }[/geshifilter-php]

Ternary operator is left-associative

Unlike in C or Java, the ternary operator associates from left to right, not from right to left. So for example, the following code will not do what you want:

[geshifilter-php] $num = 0; $text = ($num === 0) ? 'zero' : ($num === 1) ? 'one' : 'many'; // $text is now 'one' because the above call is equivalent to this: // $text = (($num === 0) ? 'zero' : ($num === 1)) ? 'one' : 'many'; [/geshifilter-php]

Comments

Simply wish to say your

Simply wish to say your article is as astonishing. The clearness for your put up is
simply spectacular and i can suppose you are an expert
on this subject. Well together with your permission allow me to grab your RSS feed to keep updated with imminent post.
Thanks 1,000,000 and please keep up the rewarding work.

You really make it appear so

You really make it appear so easy together with your presentation but I
in finding this matter to be actually something which I think I would never understand.

It seems too complex and extremely vast for me. I'm looking forward in your next publish,
I'll try to get the dangle of it!

buy cialis cialis for sale

buy cialis cialis for sale https://bumndej.com/# - buy generic cialis online online cialis buy cialis online

cialis price cialis price

cialis price cialis price https://bumndej.com/# - cialis cialis pills buy generic cialis online

I am sure this post has

I am sure this post has touched all the internet viewers, its really really fastidious piece
of writing on building up new blog.

1 harter schlag gegen die

1 harter schlag gegen die parasiten
normalisiert die funktion des magendarmtraktes
vernichtet samtliche arten von helminthen
leitet aus deinem korper die abfallprodukte der parasiten hervor.

Parasiten, die schreckliche komplikationen auslosen:

jedermann moglichen arten von invasionen in kurzester zeit
leitet aus dem korper die abfallprodukte der parasiten heraus
reinigung dieses organismus von toxinen
funktion des immunsystems, endokrinen systems, verdauungs-, nerven- und herzkreislaufsystems
vor erneuter ansteckung, bildet ein pathogenes mileau im organismus des menschen weiterhin verstarkt die abwehrkraft

parazitol sanft zu den menschen — hart fur chip helminthen
„die meisten menschen ahnen das nicht einmal, dass der organismus eines jeden zweiten mit parasiten befallen ist.
In 95 der falle lost die prasenz der helminthen keinerlei symptome proletenhaft, bis zu dem zeitpunkt, an einen sie irreparable schaden den inneren organen zugefugt haben und die funktion aller systeme des organismus gestort haben.

Gegenwartig ist nur das mittel parazitol mit der lage, den organismus vollkomen fuer beliebigen parasiten zu befreien, von denen es uber 250 arten gibt. dieses erzeugt im menschlichen organismus ein mileau, das den vorgang des parasitierens fuer sich zerstort.
Die erfahrung meiner patienten bestatigt, dass parazitol das wirksamste daruber hinaus sicherste mittel fur die vernichtung daruber hinaus ausleitung aller arten der invasionen ist auch, einschlie?lich von eiern, das keine wiederansteckung zulasst.
Die positive wirkung wird in 100 der falle erreicht.

Normalisiert die funktion des magendarmtraktes
vernichtet samtliche arten von helminthen

J Parasitologie, Mikrobiologija I Parazitologija, J Parasit Parazitol Pro Natura
Parazitol Pareri, Mikrobiologie Und Parasitologie, Mikrobiologija I Parazitologija, J Parasit Parazitol Pro Natura
Parazitol Forum, Medicinska Mikrobiologija S Parazitologijom, Parazitkapsel, Parazitol Recenze, Parazitol Pro Natura
Parazitol Bewertungen, Medicinska Mikrobiologija S Parazitologijom, J Parasitologie Parazitol Kaufen, J Parasit
Parazitol Pareri, Parazit-prospekt, J Parasit-schlagfaktor, Parazitol Bewertungen, J Parasit, Parazitol Junior Parazitol Adulti

найти человека по имени и

найти человека по имени и фамилии https://vkppl.info

поиск людей

поиск людей https://vkppl.info

поиск человека по

поиск человека по фото https://vkppl.info

поиск людей вконтакте без

поиск людей вконтакте без регистрации https://vkppl.info

найти человека по имени и

найти человека по имени и фамилии https://vkppl.info

Последние новости,

Последние новости, интерактивная карта онлайн, подробная статистика по странам в таблице.
https://covid-monitor.com

сколько заболевших коронавирусом данные

Последние новости,

Последние новости, интерактивная карта онлайн, подробная статистика по странам в таблице.
https://covid-monitor.com

коронавирус 2020

Последние новости,

Последние новости, интерактивная карта онлайн, подробная статистика по странам в таблице.
https://covid-monitor.com

мир май коронавирус

Последние новости,

Последние новости, интерактивная карта онлайн, подробная статистика по странам в таблице.
https://covid-monitor.com

карта коронавируса онлайн сегодня +на русском языке

Последние новости,

Последние новости, интерактивная карта онлайн, подробная статистика по странам в таблице.
https://covid-monitor.com

сколько людей заболеет коронавирусом +в россии

lowest interest rates on car

lowest interest rates on car loans carloansjbr best online car loans

bbt used car loans best car

bbt used car loans best car loans used car loans nj

car loans defaults

car loans defaults http://carloansjbr.com/ car loans with bad credit and repossession

bad credit car loans in pa

bad credit car loans in pa current rates for car loans bad credit car loans utah

student car loans without a

student car loans without a job car loans for college student fair credit car loans

Hey there! I just wanted to

Hey there! I just wanted to ask if you ever have any issues with hackers?
My last blog (wordpress) was hacked and I ended up losing several weeks of
hard work due to no back up. Do you have any solutions to prevent hackers?

car loans with bad credit and

car loans with bad credit and no money down cash loans for car title prequalified car loans

best bad credit car loans car

best bad credit car loans car loans with bad credit car title loans completely online

acceptance car loans low

acceptance car loans low interest car loans for bad credit title loans without seeing car

disability car loans title

disability car loans title max car loans car title loans repossession

refinancing car loans for bad

refinancing car loans for bad credit car title loans in michigan simple car loans

car title loans atlanta car

car title loans atlanta car loans calculator chase used car loans rates

Keep this going please, great

Keep this going please, great job!

ussa car loans car loans car

ussa car loans car loans car loans 4 u

bad credit car loans nc car

bad credit car loans nc car loans santander bank car loans

84 month car loans

84 month car loans http://carloansjbr.com/ bank of america car loans

car title loans toledo ohio

car title loans toledo ohio car loans calculator onpoint car loans

banks that approve bad credit

banks that approve bad credit car loans how do bank car loans work nissan car loans

What's up, this weekend is

What's up, this weekend is pleasant in favor of me, as this
moment i am reading this fantastic educational post here
at my residence.

banks that refinance car

banks that refinance car loans car loans bad credit chase car loans calculator

888poker online poker real

888poker online poker real money online poker us real money online poker sites\

free poker online games best

free poker online games best online poker bonus online poker games for real money\

learning poker online pa

learning poker online pa online poker poker online free game\

play poker for fun online

play poker for fun online online poker real money free bonus making money playing poker online\

spela casino online gratis

spela casino online gratis maryland live casino events online casino mit bonus. win palace online casino ruleta casino online., goldennugget casino online best usa online casino no deposit bonus.
vegas strip online casino 888 casino live governor of poker 3 - texas holdem casino online

casino online free movie

casino online free movie online casino with free bonus without deposit online casino play casino games. casino slot games online online casino games kostenlos., resort casino online stargames online casino.
free online casino slots with bonus rounds free online casino games for fun no download best online roulette casino

casino online free games

casino online free games sugarhouse casino online online casino real money. 888 online casino nj river belle casino online., casino online casino casino movie online.
online casino reviews #1 site for best online casinos jackpot party casino game online for free virgin casino online

make money online casino

make money online casino online live roulette casino online novoline casino. bogota online casino casino games free play online., online casino poland hollywood casino free online slots.
online casino live games casino game online uk fantasy springs online casino

island casino online 888

island casino online 888 casino live casino movie online. gta online casino car viva slots vegas™ free slot casino games online., free casino games online to play without downloading svenskt casino online.
online casino us online casino usa no deposit bonus download casino online

gambling sites online

gambling sites online michigan online gambling online gambling industry
online gambling sites no deposit online gambling laws united states online gambling laws
gambling slots online pa online gambling online gambling fake money

gambling online free money pa

gambling online free money pa online gambling top online gambling casinos
is online gambling safe online gambling pa online gambling risks and statistics
legal online sports gambling pa online gambling gta online gambling

compulsive online gambling

compulsive online gambling and pornography are examples of ____. online sports gambling online gambling in michigan
massachusetts online gambling online sports gambling disputing credit card charges online gambling
is online gambling legal in iowa online poker gambling safe port act online gambling

is online gambling legal in

is online gambling legal in maryland online gambling new jersey pros and cons of online gambling
delaware online gambling washington state online gambling online super bowl gambling
is online gambling legal in missouri pa online gambling gambling addiction help online

is online gambling legal in

is online gambling legal in the united states best online gambling sites which states allow online gambling
online gambling no deposit required legality online gambling online gambling legal issues
nj gambling online us online gambling sites free gambling online for real money

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Internal paths in double quotes, written as "internal:node/99", for example, are replaced with the appropriate absolute URL or relative path.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <del> <img>
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
  • Allowed HTML tags: <a> <blockquote> <br> <cite> <code> <dd> <del> <div> <dl> <dt> <em> <li> <ol> <p> <span> <strong> <ul>
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <bash>, <c>, <cpp>, <drupal5>, <drupal6>, <java>, <javascript>, <mysql>, <php>, <python>, <ruby>, <sql>. The supported tag styles are: <foo>, [foo].
  • Each email address will be obfuscated in a human readable fashion or (if JavaScript is enabled) replaced with a spamproof clickable link.