Wednesday, July 11, 2012

PHP and consistency? No way

Today I was debugging my PHP code and trying to figure out why my references (quite nasty feature of PHP but sometimes required) do not work only to learn that my bug was in array_key_exists function call.

So, try to guess what are the arguments for array_key_exists. If you think it is

array_key_exists($array, $key)

you are quite wrong, just read the documentation:

array_key_exists ( mixed $key , array $search )

You may say, ok, this is just a convention. Well, not exactly, looking at the manual, one can summarize the functions as following:

array array_change_key_case ( array $input [, int $case = CASE_LOWER ] )
array array_chunk ( array $input , int $size [, bool $preserve_keys = false ] )

vs

array array_combine ( array $keys , array $values )
array array_fill_keys ( array $keys , mixed $value )
mixed array_search ( mixed $needle , array $haystack [, bool $strict = false ] )
bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )


But the best part is this (can you spot the black sheep?):
array array_filter ( array $input [, callable $callback = "" ] )
array array_map ( callable $callback , array $arr1 [, array $... ] )
mixed array_reduce (array $input, callable $function [, mixed $initial = NULL ] )

In summary, PHP requires a manual, unless you are good at guessing/coin flipping.

Bonus from the manual:

string implode ( string $glue , array $pieces )
string implode ( array $pieces )


Join array elements with a glue string. Noteimplode() can, for historical reasons, accept its parameters in either order. For consistency with explode(), however, it may be less confusing to use the documented order of arguments.

No comments:

Post a Comment