With over 3400 available built-in function, PHP offers a tremendously rich environment. Yet, some of these functions are still unknown to most programmers. During this session, Damien Seguy will highlight a number of functions that are rarely used in PHP, but are nonetheless useful and available within standard distributions.
2. Agenda
Tips and Tricks from PHP
No need for anything else than standard distribution
All for PHP 5
( but lots of it is also valid in PHP 4 )
The month of PHP functions
3. Who is speaking?
Damien Séguy
Nexen Services, eZ publish silver partner for hosting
PHP / MySQL services
Redacteur en chef of www.nexen.net
Phather of an plush Elephpant
http://www.nexen.net/english.php
5. Random stuff
rand() and mt_rand()
array_rand() : extract info from an array
extract keys!
shuffle() : shuffle an array before deal
str_shuffle() : shuffle a string
6. Random stuff
Array
<?php (
$a = range('a','d'); [0] => c
shuffle($a); [1] => d
[2] => b
print_r($a); [3] => a
)
print_r(array_rand($a,3)); Array
(
print str_shuffle('abcdef'); [0] => 0
// eabdcf [1] => 1
?> [2] => 3
)
7. Arrays combinaisons
array_combine() : turn two arrays into one
Inverse to array_keys() and array_values()
<?php
$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);
Array
print_r($c);
(
?>
[green] => avocado
[red] => apple
[yellow] => banana
)
8. Arrays combinaisons
array_combine() : turn two arrays into one
PDO::FETCH_KEY_PAIR :
combine 2 columns in a hash
<?php
$html = file_get_contents(quot;http://www.php.net/quot;);
//'<a href=quot;http://php.netquot;>PHP</a>';
if (preg_match_all(
'#<a href=quot;(http://[^quot;/?]+/).*?>(.*?)</a>#s', $html, $r)) {
$liste = array_combine($r[2], $r[1]);
}
print_r($liste);
?>
9. Arrays as SQL
array_count_values() : makes easy stats
Works like a GROUP BY and COUNT()
<?php
$array = array(1, quot;heiquot;, 1, quot;takkquot;, quot;heiquot;);
print_r(array_count_values($array));
?>
Array
(
sort r u
[1] => 2
r u
[hei] => 2
k k kr uk
[takk] => 1
a a ar ua )
10. Arrays as SQL
Array
(
array_multisort() : sort several [0] => 2
arrays at once [1] => 3
[2] => 4
Works like a ORDER BY
[3] => 5
<?php )
$ar1 = array(5,4,3,2); Array
$ar2 = array('a','b','c','d'); (
array_multisort($ar1, $ar2); [0] => d
array_multisort($ar1, [1] => c
SORT_ASC,SORT_STRING, [2] => b
$ar2); [3] => a
?> )
11. Fast dir scans
scandir(‘/tmp’, true);
Include name sorting
Replace opendir, readdir, closedir and a loop!
glob(‘*.html’);
Simply move the loop out of sight
13. URL operations
parse_url()
break down into details
do not make any check
parse_str()
split a query string
separate and decode, as long as it can
Fill up an array or globals
16. URL validations
scheme : list your own
host : checkdnsrr() to check
path : realpath() + doc root (beware of mod_rewrite)
query : parse_str()
beware of the second argument!
don’t handle &
17. URL rebuilding
http_build_query()
rebuild your query
takes into account encoding and arrays
<?php
print http_build_query(
array_merge($_GET ,
array(' de ' => ' ')));
?>
+de+=%E5%AF%B9%E4%BA%86%EF%BC%81
19. PHP is dynamic
Variables variables
<?php
$x = 'y';
$y = 'z';
$z = 'a';
echo $x; // displays y
echo $$x; // displays z
echo $$$x; // displays a
?>
20. Variable constants
Still one definition
Dynamic constant value
<?php
define (quot;CONSTANTquot;, 'eZ Conference');
echo CONSTANT;
echo constant(quot;CONSTANTquot;);
?>
See the runkit to change constants...
22. Variable functions
<?php
$func = 'foo'; $foo = 'bar'; $class = 'bb';
$func($foo); // calling foo with bar
call_user_func($func, $foo);// same as above
call_user_func(array($class, $func), $foo);
// now with objects!
$class->$func($foo); // same as above
?>
23. Variable functions
<?php
$func = 'f';
// a function
// beware of langage construct such as empty()
$func = array('c','m');
// a static call to class c
$func = array($o,'m');
// a call to object o
call_user_func($func, $foo);
?>
24. Object magic
__autoload() : load classes JIT
__sleep() and __wakeup()
Store object and ressources in sessions
__toString() : to turn an object to a string
__toArray() : get_object_vars($object);
__toInteger() : may be?
25. Output buffering
Avoid ‘already sent’ bug
Clean it : tidy
<?php
Compress it : gz
ob_start(quot;ob_gzhandlerquot;);
Cache it echo quot;Hellonquot;;
setcookie(quot;cquot;, quot;vquot;);
ob_end_flush();
?>
27. Connexion handling
PHP maintains the connexion status
0 Normal; 1 Aborted; 2 Timeout
ignore_user_abort() to make a script without interruption
connexion_status() to check status
28. Register for shutdown
Function executed at script shutdown
Correct closing of resources
More convenient than ignore_user_abort() a library
In OOP, better use __destruct()
Storing calculated variables
30. Assertions
Include tests during execution
Assertion are an option (default is on) :
Most clever way than removing than echo/var_dump
Common practice in other languages
Programmation by contract
32. Debugging
get_memory_usage()
memory_limit is now on by default
Better memory handling
The fake growth of memory needs
get_peak_memory_usage()
33. Debugging
get_included_files()
get_defined_constants/functions/vars()
get_declared_classes()
get_debug_backtrace()
function stack and their arguments
file and line calling