SlideShare una empresa de Scribd logo
1 de 117
Descargar para leer sin conexión
PHP TIPS & TRICKS


        1
PHP TIPS & TRICKS
             AKA
JOURNEY INTO DEPTHS OF MANUAL


             2
name: Radosław Benkel
                          nick: singles
                          www: http://www.rbenkel.me
                          twitter: @singlespl *




* and I have nothing in common with http://www.singles.pl ;]

                                   3
DEVELOPERS OFFEN WRITE
     FUNCTIONS FOR
SOMETHING, THAT ALREADY
         EXISTS.


           4
WHY?




 5
WHY?

SOMETIMES THEY WANT TO
 DO SOMETHING BETTER.




          6
WHY?

SOMETIMES THEY WANT TO
 DO SOMETHING BETTER.

OR JUST DON'T KNOW THAT
   SOMETHING ALREADY
         EXISTS.
           7
SOME OF THESE YOU MAY
       KNOW.




          8
SOME OF THESE YOU MAY
       KNOW.

    SOME DON'T.




          9
SOME OF THESE YOU MAY
        KNOW.

      SOME DON'T.

  IF YOU KNOW BETTER
SOLUTION, PLEASE SHARE :)

            10
SHORT TERNARY
  OPERATOR



      11
SHORT TERNARY OPERATOR




$var = 'SomeValue';

$output = $var ? $var : 'default';

$output = $var ?: 'default'; //PHP >= 5.3




                      12
DIRECTORY LISTING




        13
DIRECTORY LISTING #1


$dir = "/application/modules/*";
if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        while (($file = readdir($dh)) !== false) {
            echo "Filename is: " . $file . PHP_EOL;
        }
        closedir($dh);
    }
}




                           14
DIRECTORY LISTING #2




$dir = "/application/modules/*";
foreach(glob($dir) as $file) {
    echo "Filename is: " . $file . PHP_EOL;
}




                           15
DIRECTORY LISTING #3




$dir = "/application/modules/";
foreach (new DirectoryIterator($dir) as $fileInfo) {
    echo "Filename is: " . $fileInfo->getFilename() . PHP_EOL;
}




                                    16
DIRECTORY LISTING #3


$dir = "/application/modules/";
foreach (new DirectoryIterator($dir) as $fileInfo) {
    echo "Filename is: " . $fileInfo->getFilename() . PHP_EOL;
}




                   andlotofothers:
            http://www.php.net/manual/en/
              class.directoryiterator.php

                                    17
EXPLODED STRING VALUES




          18
EXPLODED STRING VALUES

$string = 'bazinga.foo.bar.suitup!'

$values     = explode('.', $string);
$sheldon    = $values[0]; //bazinga
$barney     = $values[3]: //suitup

list($sheldon, , , $barney) = explode('.', $string);

//PHP 5.4 stuff
$sheldon = explode('.', $string)[0];
$barney = explode('.', $string)[3];




                           19
FILEPATH INFORMATION




         20
FILEPATH INFORMATION

$path = '/some/directory/in/filesystem/file.some.txt';
$parts = explode('/', $path);
$partsCopy = $parts;
array_pop($partsCopy);

// '/some/directory/in/filesystem'
$filePath = implode('/', $partsCopy);
$fileExtension = explode('.', $parts[count($parts) - 1]);

// 'txt'
$fileExtension = $fileExtension[count($fileExtension)-1];




                           21
FILEPATH INFORMATION

     Butwhy?



           22
FILEPATH INFORMATION


$path = '/some/directory/in/filesystem/file.some.txt';

$fileInfo = pathinfo($path);
$fileInfo['dirname']    === pathinfo($path,   PATHINFO_DIRNAME);
$fileinfo['basename']   === pathinfo($path,   PATHINFO_BASENAME);
$fileinfo['extension'] === pathinfo($path,    PATHINFO_EXTENSION);
$fileinfo['filename']   === pathinfo($path,   PATHINFO_FILENAME);




                                23
FIRST NOT EMPTY VARIABLE




           24
FIRST NOT EMPTY VARIABLE
          AKA
      COALESCE, NVL



           25
FIRST NOT EMPTY VARIABLE

$a   =   null;
$b   =   false;
$c   =   14;
$d   =   'foo';

$notEmpty = $a ?: $b ?: $c ?: $d;
echo $notEmpty // 14



                  26
DEEP VAR INTERPOLATION




          27
DEEP VAR INTERPOLATION
$obj = new stdClass();
$obj-some = 'hello';
$obj-foo = new stdClass();
$obj-foo-bar = 123;

echo Value is $obj-some;

//Object of class stdClass could not be converted to string in
echo Value is $obj-foo-bar;
//Value is 123
echo Value is {$obj-foo-bar};

//Same for array
$ar = array('some' = 'var');
echo Value is $ar['some']; //syntax error
echo Value is {$ar['some']}; //Value is var




                                28
MULTIPLE ISSET




      29
MULTIPLE ISSET


$val = null;
$var = true;

if (isset($not_defined)  isset($val)  isset($var)) {
    /* ... */
}




                           30
MULTIPLE ISSET
if (isset($not_defined)  isset($val)  isset($var)) {
    /* ... */
}




                        ===

if (isset($not_defined, $val, $var)) {
    /* ... */
}



                           31
FILTER_INPUT




     32
FILTER_INPUT



$action = isset($_POST['action'])
                ? some_validate($_POST['action'])
                : 'default_action';




                           33
FILTER_INPUT




     34
FILTER_INPUT
/* data actually came from POST
$_POST = array(
    'product_id'    = 'libgdscript',
    'component'     = '10',
    'versions'      = '2.0.33',
    'testscalar'    = array('2', '23', '10', '12'),
    'testarray'     = '2',
);
*/
$args = array(
    'product_id'   = FILTER_SANITIZE_ENCODED,
    'component'    = array(
        'filter'    = FILTER_VALIDATE_INT,
        'flags'     = FILTER_REQUIRE_ARRAY,
        'options'   = array('min_range' = 1, 'max_range' = 10)
    ),
    'versions'     = FILTER_SANITIZE_ENCODED,
    'doesnotexist' = FILTER_VALIDATE_INT,
    'testscalar'   = array(
        'filter' = FILTER_VALIDATE_INT,
        'flags' = FILTER_REQUIRE_SCALAR,
    ),
    'testarray'    = array(
        'filter' = FILTER_VALIDATE_INT,
        'flags' = FILTER_REQUIRE_ARRAY,
    )
);
$myinputs = filter_input_array(INPUT_POST, $args);




                                                       35
STRING CONCATENATION




         36
STRING CONCATENATION




  TIME F OR R IDDLE!

                 37
STRING CONCATENATION




 WHO K NOWS W HAT'S T HAT?



                       38
STRING CONCATENATION

 WHO K NOWS W HAT'S T HAT?




                        39
STRING CONCATENATION




     CORRECT!

         40
STRING CONCATENATION




         41
STRING CONCATENATION

$a   =   'scissors';
$b   =   'paper';
$c   =   'rock';
$d   =   'lizard';
$e   =   'Spock';

$rules = $a . ' cut ' . $b . ', ' . $b . ' covers ' .
$c . ', ' . $c . ' crushes ' . $d . ', ' . $d . '
poisons ' . $e . '...';
echo $rules;
//scissors cut paper, paper covers rock, rock crushes
lizard, lizard poisons Spock...




                           42
STRING CONCATENATION

$a   =   'scissors';
$b   =   'paper';
$c   =   'rock';
$d   =   'lizard';
$e   =   'Spock';

$rules = $a cut $b, $b covers $c, $c crushes $d, $d
poisons $e...;
echo $rules;
//scissors cut paper, paper covers rock, rock crushes
lizard, lizard poisons Spock...




                           43
STRING CONCATENATION

$a   =   'scissors';
$b   =   'paper';
$c   =   'rock';
$d   =   'lizard';
$e   =   'Spock';

$rules = %s cut %s, %s covers %s, %s crushes %s, %s poisons %s...;
echo sprintf($rules, $a, $b, $b, $c, $c, $d, $d, $e);
echo vsprintf($rules, array($a, $b, $b, $c, $c, $d, $d, $e));
printf($rules, $a, $b, $b, $c, $c, $d, $d, $e);
vprintf($rules, array($a, $b, $b, $c, $c, $d, $d, $e));
//4x scissors cut paper, paper covers rock, rock crushes lizard, lizard
poisons Spock...




                                    44
STRING CONCATENATION


  WHY U SE P RINTF
 FAMILY F UNCTIONS,
WHEN W E H AVE S TRING
  INTERPOLATION?
                         45
STRING CONCATENATION



 STRING PATTERN REUSE
(CONNECTION STRINGS, API CALLS,
           ETC.)



              46
STRING CONCATENATION

 LOT OF FORMATTING OPTIONS




            47
QUICK OBJECT DEFINITION




           48
QUICK OBJECT DEFINITION


$obj = new stdClass();
$obj-foo = 123;
$obj-bar = 'some';

//or (btw. not recursive!)
$obj = (object)array('foo' = 123, 'bar' = 'some');

// unfortunately - not possible :(
$obj = {'foo' = 123}




                           49
ENUM




 50
ENUM
class Roles {
    const ADMIN     = 1;
    const USER      = 2;
    const GUEST     = 3;
}

$class = new ReflectionClass('Roles');
var_dump($class-getConstants());

/*
array(3) {
   [ADMIN]=
   int(1)
   [USER]=
   int(2)
   [GUEST]=
   int(3)
}*/




                                    51
SPL FTW!




   52
DATE/TIME MANIPULATION




          53
DATE/TIME MANIPULATION




          54
DATE/TIME MANIPULATION


+ OBJECT/PROCEDURAL
+ TIMEZONES
+ INTERVALS
+ SOME OPERATORS
+ PHP CORE SINCE 5.2

           55
DATE/TIME MANIPULATION
$a = new DateTime('2011-12-12');
$b = new DateTime('2011-11-12');
$c = new DateTime('2011-12-12');

var_dump(($a  $b)); // false
var_dump(($a  $b)); // true
var_dump(($c == $a)); // true

// works
$a-add(new DateInterval('P2D'));
echo $a-format('Y-m-d') // echo 2011-12-14

// dont work :(
$a += new DateInterval('P2D');



                           56
DID YOU MEAN ...




        57
DID YOU MEAN ...




        58
DID YOU MEAN ...


    YOU CAN TRY:
http://php.net/manual/en/
function.levenshtein.php



            59
PARSING URL PARAMS




        60
PARSING URL PARAMS




parse_url + parse_str




          61
PARSING URL PARAMS
                          parse_url
$url = 'http://username:password@hostname/path?arg=value#anchor';
print_r(parse_url($url));
echo parse_url($url, PHP_URL_PATH); //and others, same as pathinfo
/*Array
(
    [scheme] = http
    [host] = hostname
    [user] = username
    [pass] = password
    [path] = /path
    [query] = arg=value
    [fragment] = anchor
)
/path
*/




                                    62
PARSING URL PARAMS
                            parse_str
parse_str('single=Singlecheck[]=check1check[]=fooradio=radio2', $data);
print_r($data);die();

/*Array
(
    [single] = Single
    [check] = Array
        (
            [0] = check1
            [1] = foo
        )

     [radio] = radio2
)
*/




                                    63
PARSING URL PARAMS
                            parse_str
parse_str('single=Singlecheck[]=check1check[]=fooradio=radio2', $data);
print_r($data);die();

/*Array
(
    [single] = Single
    [check] = Array
        (
            [0] = check1
            [1] = foo
        )
         DOn'tusewithoutsecondparameter!
     [radio] = radio2
)
*/




                                       64
PARSING URL PARAMS
                          parse_str
function foo() {
    parse_str('single=Singlecheck[]=check1check[]=fooradio=radio2');
    print_r(get_defined_vars());die();
}
foo();




                   Localmagicvariables!


                                     65
CSV PARSING




     66
CSV PARSING




fgetcsv + str_getcsv




         67
CSV PARSING
       fgetcsv (for big files)
$row = 1;
if (($handle = fopen(test.csv, r)) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ,)) !== FALSE) {
        $num = count($data);
        echo p $num fields in line $row: br //pn;
        $row++;
        for ($c=0; $c  $num; $c++) {
            echo $data[$c] . br /n;
        }
    }
    fclose($handle);
}
?




                                    68
CSV PARSING
str_getcsv (for smaller ones)

$line = 'AddDescription My description to the file.
filename.jpg';
$parsed = str_getcsv(
    $line, # Input line
    ' ',   # Delimiter
    '',   # Enclosure
    ''   # Escape char
);
var_dump( $parsed );




                           69
AUTO_PREPEND_FILE




        70
AUTO_PREPEND_FILE
                          php.ini
auto_prepend_file string
Specifies the name of a file that is automatically parsed before the
main file. The file is included as if it was called with the
require()function, so include_path is used.
The special value none disables auto-prepending.




                                 71
AUTO_PREPEND_FILE
                                   php.ini
auto_prepend_file string
Specifies the name of a file that is automatically parsed before the
main file. The file is included as if it was called with the
require()function, so include_path is used.
The special value none disables auto-prepending.

 Greatplaceforyourawesomemydie,dump,
                debug,pukeetc.functions.
                Butbecarefulwhendeploying.

                                             72
FILE INCLUDE




     73
FILE INCLUDE

//config.php
$dbName = 'some';
$dbPass = 'foo';
$dpPort = 123;



//index.php
include 'config.php';
echo $dbPass; //echo 'some'


                    74
FILE INCLUDE

//config.php
$dbName = 'some';
$dbPass = 'foo';
$dpPort = 123; magicvariable!
           Local

//index.php
include 'config.php';
echo $dbPass; //echo 'some'


                         75
FILE INCLUDE
//config.php
return array(
    'dbName' = 'some',
    'dbPass' = 'foo',
    'dbPort' = 123
);

//index.php
$config = include 'config.php';
echo $dbPass; //Notice 'undefined'
echo $config['dbName'] = 'some';


                     76
FILE INCLUDE

      BTW. T HIS A LSO W ORKS
//function.php
return function($data) {
    print_r($data);die();
};

//index.php
$dump = include 'function.php';
$dump(array(hello, 'moto'));


                            77
QUICK COMMENT
 WITHOUT IDE



      78
QUICK COMMENT

function foo() {
    $items = array();

    foreach (array('some', 'a') as $item) {
        if ($item === 'a') {
            continue;
        }
        $items[] = $item;
    }

    return $items;
}




                           79
QUICK COMMENT

function foo() {
    $items = array();
    /*
    foreach (array('some', 'a') as $item) {
        if ($item === 'a') {
            continue;
        }
        $items[] = $item;
    }
    */
    return $items;
}




                           80
QUICK COMMENT

function foo() {
    $items = array();
    /* */
    foreach (array('some', 'a') as $item) {
        if ($item === 'a') {
            continue;
        }
        $items[] = $item;
    }
    /* */
    return $items;
}




                           81
QUICK COMMENT

function foo() {
    $items = array();
    /* *
    foreach (array('some', 'a') as $item) {
         if ($item === 'a') {
             continue;
         }
         $items[] = $item;
    }
    /* */
    return $items;
}




                           82
QUICK COMMENT

function foo() {
    $items = array();
    /* *
    foreach (array('some', 'a') as $item) {
         if ($item === 'a') {
           Anotheroptionsalsopossible
             continue;
         }
         $items[] = $item;
    }
    /* */
    return $items;
}




                                  83
ONE LINE VARIABLE SWAP




          84
ONE LINE VARIABLE SWAP

$a = 123;
$b = 987;

list($a, $b) = array($b, $a);

echo $a; //987
echo $b; //123

//or
$a ^= $b ^= $a ^= $b;
//http://betterexplained.com/articles/swap-two-variables-using-xor/




                                 85
COMPACT + EXTRACT




        86
COMPACT + EXTRACT

function index() {
    $user = Users::find(1);
    $items = Items::getAllForUser($user);
    return $this-render('index.twig', array(
        'user' = $user,
        'items' = $items
    ));

    //same as
    return $this-render('index.twig', compact('user', 'items'));
}




                                 87
COMPACT + EXTRACT


function foo() {
    $data = array('some' = 'asa', 'foo' = 'asda');
    extract($data);
    var_dump(get_defined_vars());die();
}
foo();




                                 88
COMPACT + EXTRACT


function foo() {
    $data = array('some' = 'asa', 'foo' = 'asda');
    extract($data);
    var_dump(get_defined_vars());die();
}
foo();




          Onceagainlocalmagicvariables!

                                         89
FIRST ARRAY ELEMENT WITH
     ASSOCIATIVE KEYS



           90
FIRST ARRAY ELEMENT
$data = array(
    'foo' = 123,
    'bar' = 1987,
    'wee' = 'ugh'
);

//echo $data[0]; //undefined offset
echo reset($data); //123
echo current($data); //123

reset($data);
list(,$value) = each($data);
echo $value; //123

list($value) = array_values($data);
echo $value; //123

echo array_shift($data); //123 - caution - modifies array
//solution?
echo array_shift(array_values($data)); //123 without modifying array




                                         91
RANDOM ARRAY ITEM




        92
RANDOM ARRAY ITEM
$data = array(
    'foo' = 123,
    'bar' = 1987,
    'wee' = 'ugh'
);

// not like that - works only for number indexed arrays
without gaps !
$random = $data[rand(0, count($data) - 1)];
// or that way - array_rand returns key, not value!
$random = array_rand($data);

// that way - works always
$random = $data[array_rand($data)];



                          93
MULTIPLE VALUE CHECK




         94
MULTIPLE VALUE CHECK


$person = 'Barney';

if ($person == 'Joey' || $person == 'Rachel' || $person == 'Ross'
    || $person == 'Phoebe' || $person == 'Monica' || $person == 'Chandler'
) {
    echo 'Best comedy show ever';
} else if ($person == 'Barney' || $person == 'Ted'
           || $person == 'Lily' || $person == 'Marshal'
           || $person == 'Robin'
) {
    echo 'Copy of best comedy show ever, but still good one';
} else {
    echo 'Maybe another good show';
}




                                    95
MULTIPLE VALUE CHECK

$person = 'Barney';

switch ($person) {
    case 'Joey':
    case 'Rachel':
    case 'Ross':
    /* ... */
        echo 'Best comedy show ever';
        break;
    case 'Barney';
    case 'Ted';
    /* ... */
        echo 'Like a copy of best show ever, but still good one';
        break;
    default:
        echo 'Maybe another good show';
}




                                    96
MULTIPLE VALUE CHECK


$person = 'Barney';

if (in_array($person, array('Joey', 'Rachel', 'Ross', 'Phoebe', 'Monica',
'Chandler')))
) {
    echo 'Best comedy show ever';
} else if (in_array($person, array('Barney', 'Ted', 'Lily', 'Marshal',
'Robin')))
) {
    echo 'Like a copy of best comedy show ever, but still good one';
} else {
    echo 'Maybe another good show';
}




                                    97
MULTIPLE VALUE CHECK
                      BTW!



in_array($needle, $haystack) works like '=='
in_array($needle, $haystack, true) works like '==='




                         98
EMPTY ARRAY CHECK




        99
EMPTY ARRAY CHECK

$input = array();

//it will work
if (is_array($input)  count($input) === 0) {

}

//via @wookiebpl
if ($input === array()) {

}




                            100
EMPTY ARRAY CHECK



//why not '=='?
if ($input == array()) {

}




                           101
EMPTY ARRAY CHECK




http://php.net/manual/en/types.comparisons.php

                     102
INNER ARRAYS OPERATIONS




          103
INNER ARRAYS OPERATIONS


$shopCartPrices = array(
    1 = 123.12,
    4 = 23.34,
    6 = 99.23
);

//sum? basic stuff.
$sum = array_sum($shopCartPrices);




                                     104
INNER ARRAYS OPERATIONS




    BUT SOMETIMES...



           105
INNER ARRAYS OPERATIONS




          106
INNER ARRAYS OPERATIONS




          107
INNER ARRAYS OPERATIONS

$shopCartPrices   = array(
    1 = array(
        'price'   = 123.12
    ),
    4 = array(
        'price'   = 23.34
    ),
    6 = array(
        'price'   = 99.23
    )
);

//sure. you can do that
$sum = 0;
foreach ($shopCartPrices as $cartItem) {
    $sum += $cartItem['price'];
}




                                    108
INNER ARRAYS OPERATIONS

$shopCartPrices   = array(
    1 = array(
        'price'   = 123.12
    ),
    4 = array(
        'price'   = 23.34
    ),
    6 = array(
        'price'   = 99.23
    )
);



//but you can do better = PHP = 5.3
$sum = array_sum(array_map(function($cartItem) {
    return $cartItem['price'];
}, $shopCartPrices));




                                    109
INNER ARRAYS OPERATIONS


 BUT W ITH T HIS O NE, P EOPLE
   OFTEN L OOK A T M E L IKE 
SOMEONE W HO'S U SING M AGIC.


                                     110
INNER ARRAYS OPERATIONS
        OR F ORCE




               111
INNER ARRAYS OPERATIONS

$shopCartPrices   = array(
    1 = array(
        'price'   = 123.12
    ),
    4 = array(
        'price'   = 23.34
    ),
    6 = array(
        'price'   = 99.23
    )
);




//and sometimes, even better - without PHP 5.3
$sum = array_sum(array_map('array_pop', $shopCartPrices));




                                    112
LAST R IDDLE


         113
$var = 'a';
for($i = 0; $i  150; $i++) {
    $var++;
    echo $var, ' ';
}

//output?




                                114
$var = 'a';
for($i = 0; $i  150; $i++) {
    $var++;
    echo $var, ' ';
}

//output?

//b c   d e f   g h i   j k l   m n o   p q r   s t u   v w x   y z aa ab ac ad ae af ag ah
ai aj   ak al   am an   ao ap   aq ar   as at   au av   aw ax   ay az ba bb bc bd be bf bg
bh bi   bj bk   bl bm   bn bo   bp bq   br bs   bt bu   bv bw   bx by bz ca cb cc cd ce cf
cg ch   ci cj   ck cl   cm cn   co cp   cq cr   cs ct   cu cv   cw cx cy cz da db dc dd de
df dg   dh di   dj dk   dl dm   dn do   dp dq   dr ds   dt du   dv dw dx dy dz ea eb ec ed
ee ef   eg eh   ei ej   ek el   em en   eo ep   eq er   es et   eu




                                                115
IT'S N OT A  B UG.
IT'S A  F EATURE : ]

                       116
117

Más contenido relacionado

La actualidad más candente

News of the Symfony2 World
News of the Symfony2 WorldNews of the Symfony2 World
News of the Symfony2 World
Fabien Potencier
 
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Masahiro Nagano
 
Dependency injection - phpday 2010
Dependency injection - phpday 2010Dependency injection - phpday 2010
Dependency injection - phpday 2010
Fabien Potencier
 

La actualidad más candente (20)

Introdução ao Perl 6
Introdução ao Perl 6Introdução ao Perl 6
Introdução ao Perl 6
 
Teaching Your Machine To Find Fraudsters
Teaching Your Machine To Find FraudstersTeaching Your Machine To Find Fraudsters
Teaching Your Machine To Find Fraudsters
 
Symfony2 - WebExpo 2010
Symfony2 - WebExpo 2010Symfony2 - WebExpo 2010
Symfony2 - WebExpo 2010
 
News of the Symfony2 World
News of the Symfony2 WorldNews of the Symfony2 World
News of the Symfony2 World
 
C99
C99C99
C99
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate Frameworks
 
My shell
My shellMy shell
My shell
 
Debugging: Rules And Tools - PHPTek 11 Version
Debugging: Rules And Tools - PHPTek 11 VersionDebugging: Rules And Tools - PHPTek 11 Version
Debugging: Rules And Tools - PHPTek 11 Version
 
Get into the FLOW with Extbase
Get into the FLOW with ExtbaseGet into the FLOW with Extbase
Get into the FLOW with Extbase
 
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
 
Functional programming with php7
Functional programming with php7Functional programming with php7
Functional programming with php7
 
PHP and MySQL
PHP and MySQLPHP and MySQL
PHP and MySQL
 
Dependency injection - phpday 2010
Dependency injection - phpday 2010Dependency injection - phpday 2010
Dependency injection - phpday 2010
 
Document Classification In PHP
Document Classification In PHPDocument Classification In PHP
Document Classification In PHP
 
Document Classification In PHP - Slight Return
Document Classification In PHP - Slight ReturnDocument Classification In PHP - Slight Return
Document Classification In PHP - Slight Return
 
You code sucks, let's fix it
You code sucks, let's fix itYou code sucks, let's fix it
You code sucks, let's fix it
 
PHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object CalisthenicsPHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object Calisthenics
 
R57.Php
R57.PhpR57.Php
R57.Php
 
Nop2
Nop2Nop2
Nop2
 
Design Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleDesign Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et Pimple
 

Destacado

Manipal Digital Systems_Portfolio
Manipal Digital Systems_PortfolioManipal Digital Systems_Portfolio
Manipal Digital Systems_Portfolio
Kingoffame
 
Chapter 1.1 Columbus, The Indians, and Human Progress
Chapter 1.1 Columbus, The Indians, and Human ProgressChapter 1.1 Columbus, The Indians, and Human Progress
Chapter 1.1 Columbus, The Indians, and Human Progress
Melody Kearney
 
R042 0212 Hob Achterhoek Liemers
R042 0212 Hob Achterhoek LiemersR042 0212 Hob Achterhoek Liemers
R042 0212 Hob Achterhoek Liemers
JohanKraaijinga
 
c.v May 2016
c.v May 2016c.v May 2016
c.v May 2016
ahmed ali
 

Destacado (20)

Presentcontinuous
PresentcontinuousPresentcontinuous
Presentcontinuous
 
Caso fauto
Caso fautoCaso fauto
Caso fauto
 
Acuerdo+13+de+nov+15+de+2011+ca
Acuerdo+13+de+nov+15+de+2011+caAcuerdo+13+de+nov+15+de+2011+ca
Acuerdo+13+de+nov+15+de+2011+ca
 
Trans
TransTrans
Trans
 
Manipal Digital Systems_Portfolio
Manipal Digital Systems_PortfolioManipal Digital Systems_Portfolio
Manipal Digital Systems_Portfolio
 
EL COMUNAL N° 1
EL COMUNAL N° 1EL COMUNAL N° 1
EL COMUNAL N° 1
 
El ale es un makina
El ale es un makina El ale es un makina
El ale es un makina
 
Opimerad SCM i SAP
Opimerad SCM i SAPOpimerad SCM i SAP
Opimerad SCM i SAP
 
Seguridad informática
Seguridad informáticaSeguridad informática
Seguridad informática
 
Juan carlos vidal
Juan carlos vidalJuan carlos vidal
Juan carlos vidal
 
Chapter 1.1 Columbus, The Indians, and Human Progress
Chapter 1.1 Columbus, The Indians, and Human ProgressChapter 1.1 Columbus, The Indians, and Human Progress
Chapter 1.1 Columbus, The Indians, and Human Progress
 
Anatomie d'un email - E-commerce
Anatomie d'un email - E-commerceAnatomie d'un email - E-commerce
Anatomie d'un email - E-commerce
 
R042 0212 Hob Achterhoek Liemers
R042 0212 Hob Achterhoek LiemersR042 0212 Hob Achterhoek Liemers
R042 0212 Hob Achterhoek Liemers
 
Step 4 altitude
Step 4   altitude Step 4   altitude
Step 4 altitude
 
Placement Brochure
Placement BrochurePlacement Brochure
Placement Brochure
 
Hic Et Nunc Presentazione 5 2012
Hic Et Nunc Presentazione  5 2012Hic Et Nunc Presentazione  5 2012
Hic Et Nunc Presentazione 5 2012
 
c.v May 2016
c.v May 2016c.v May 2016
c.v May 2016
 
Univerteam esspañol 2015
Univerteam esspañol 2015Univerteam esspañol 2015
Univerteam esspañol 2015
 
De pirujas
De pirujasDe pirujas
De pirujas
 
The great debaters
The great debatersThe great debaters
The great debaters
 

Similar a PHP Tips & Tricks

Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
Kang-min Liu
 
Crazy things done on PHP
Crazy things done on PHPCrazy things done on PHP
Crazy things done on PHP
Taras Kalapun
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
Stoyan Stefanov
 
Barely Legal Xxx Perl Presentation
Barely Legal Xxx Perl PresentationBarely Legal Xxx Perl Presentation
Barely Legal Xxx Perl Presentation
Attila Balazs
 
R57php 1231677414471772-2
R57php 1231677414471772-2R57php 1231677414471772-2
R57php 1231677414471772-2
ady36
 

Similar a PHP Tips & Tricks (20)

Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
 
Crazy things done on PHP
Crazy things done on PHPCrazy things done on PHP
Crazy things done on PHP
 
The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistence
 
Bag of tricks
Bag of tricksBag of tricks
Bag of tricks
 
The most exciting features of PHP 7.1
The most exciting features of PHP 7.1The most exciting features of PHP 7.1
The most exciting features of PHP 7.1
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
 
Perl Bag of Tricks - Baltimore Perl mongers
Perl Bag of Tricks  -  Baltimore Perl mongersPerl Bag of Tricks  -  Baltimore Perl mongers
Perl Bag of Tricks - Baltimore Perl mongers
 
Smelling your code
Smelling your codeSmelling your code
Smelling your code
 
How to write code you won't hate tomorrow
How to write code you won't hate tomorrowHow to write code you won't hate tomorrow
How to write code you won't hate tomorrow
 
Hidden treasures of Ruby
Hidden treasures of RubyHidden treasures of Ruby
Hidden treasures of Ruby
 
How to stand on the shoulders of giants
How to stand on the shoulders of giantsHow to stand on the shoulders of giants
How to stand on the shoulders of giants
 
Node.js for PHP developers
Node.js for PHP developersNode.js for PHP developers
Node.js for PHP developers
 
mro-every.pdf
mro-every.pdfmro-every.pdf
mro-every.pdf
 
Php 102: Out with the Bad, In with the Good
Php 102: Out with the Bad, In with the GoodPhp 102: Out with the Bad, In with the Good
Php 102: Out with the Bad, In with the Good
 
Barely Legal Xxx Perl Presentation
Barely Legal Xxx Perl PresentationBarely Legal Xxx Perl Presentation
Barely Legal Xxx Perl Presentation
 
BASH Variables Part 1: Basic Interpolation
BASH Variables Part 1: Basic InterpolationBASH Variables Part 1: Basic Interpolation
BASH Variables Part 1: Basic Interpolation
 
Redis for the Everyday Developer
Redis for the Everyday DeveloperRedis for the Everyday Developer
Redis for the Everyday Developer
 
R57php 1231677414471772-2
R57php 1231677414471772-2R57php 1231677414471772-2
R57php 1231677414471772-2
 
Barcelona.pm Curs1211 sess01
Barcelona.pm Curs1211 sess01Barcelona.pm Curs1211 sess01
Barcelona.pm Curs1211 sess01
 
Why async and functional programming in PHP7 suck and how to get overr it?
Why async and functional programming in PHP7 suck and how to get overr it?Why async and functional programming in PHP7 suck and how to get overr it?
Why async and functional programming in PHP7 suck and how to get overr it?
 

Último

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Último (20)

WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 

PHP Tips & Tricks

  • 1. PHP TIPS & TRICKS 1
  • 2. PHP TIPS & TRICKS AKA JOURNEY INTO DEPTHS OF MANUAL 2
  • 3. name: Radosław Benkel nick: singles www: http://www.rbenkel.me twitter: @singlespl * * and I have nothing in common with http://www.singles.pl ;] 3
  • 4. DEVELOPERS OFFEN WRITE FUNCTIONS FOR SOMETHING, THAT ALREADY EXISTS. 4
  • 6. WHY? SOMETIMES THEY WANT TO DO SOMETHING BETTER. 6
  • 7. WHY? SOMETIMES THEY WANT TO DO SOMETHING BETTER. OR JUST DON'T KNOW THAT SOMETHING ALREADY EXISTS. 7
  • 8. SOME OF THESE YOU MAY KNOW. 8
  • 9. SOME OF THESE YOU MAY KNOW. SOME DON'T. 9
  • 10. SOME OF THESE YOU MAY KNOW. SOME DON'T. IF YOU KNOW BETTER SOLUTION, PLEASE SHARE :) 10
  • 11. SHORT TERNARY OPERATOR 11
  • 12. SHORT TERNARY OPERATOR $var = 'SomeValue'; $output = $var ? $var : 'default'; $output = $var ?: 'default'; //PHP >= 5.3 12
  • 14. DIRECTORY LISTING #1 $dir = "/application/modules/*"; if (is_dir($dir)) { if ($dh = opendir($dir)) { while (($file = readdir($dh)) !== false) { echo "Filename is: " . $file . PHP_EOL; } closedir($dh); } } 14
  • 15. DIRECTORY LISTING #2 $dir = "/application/modules/*"; foreach(glob($dir) as $file) { echo "Filename is: " . $file . PHP_EOL; } 15
  • 16. DIRECTORY LISTING #3 $dir = "/application/modules/"; foreach (new DirectoryIterator($dir) as $fileInfo) { echo "Filename is: " . $fileInfo->getFilename() . PHP_EOL; } 16
  • 17. DIRECTORY LISTING #3 $dir = "/application/modules/"; foreach (new DirectoryIterator($dir) as $fileInfo) { echo "Filename is: " . $fileInfo->getFilename() . PHP_EOL; } andlotofothers: http://www.php.net/manual/en/ class.directoryiterator.php 17
  • 19. EXPLODED STRING VALUES $string = 'bazinga.foo.bar.suitup!' $values = explode('.', $string); $sheldon = $values[0]; //bazinga $barney = $values[3]: //suitup list($sheldon, , , $barney) = explode('.', $string); //PHP 5.4 stuff $sheldon = explode('.', $string)[0]; $barney = explode('.', $string)[3]; 19
  • 21. FILEPATH INFORMATION $path = '/some/directory/in/filesystem/file.some.txt'; $parts = explode('/', $path); $partsCopy = $parts; array_pop($partsCopy); // '/some/directory/in/filesystem' $filePath = implode('/', $partsCopy); $fileExtension = explode('.', $parts[count($parts) - 1]); // 'txt' $fileExtension = $fileExtension[count($fileExtension)-1]; 21
  • 22. FILEPATH INFORMATION Butwhy? 22
  • 23. FILEPATH INFORMATION $path = '/some/directory/in/filesystem/file.some.txt'; $fileInfo = pathinfo($path); $fileInfo['dirname'] === pathinfo($path, PATHINFO_DIRNAME); $fileinfo['basename'] === pathinfo($path, PATHINFO_BASENAME); $fileinfo['extension'] === pathinfo($path, PATHINFO_EXTENSION); $fileinfo['filename'] === pathinfo($path, PATHINFO_FILENAME); 23
  • 24. FIRST NOT EMPTY VARIABLE 24
  • 25. FIRST NOT EMPTY VARIABLE AKA COALESCE, NVL 25
  • 26. FIRST NOT EMPTY VARIABLE $a = null; $b = false; $c = 14; $d = 'foo'; $notEmpty = $a ?: $b ?: $c ?: $d; echo $notEmpty // 14 26
  • 28. DEEP VAR INTERPOLATION $obj = new stdClass(); $obj-some = 'hello'; $obj-foo = new stdClass(); $obj-foo-bar = 123; echo Value is $obj-some; //Object of class stdClass could not be converted to string in echo Value is $obj-foo-bar; //Value is 123 echo Value is {$obj-foo-bar}; //Same for array $ar = array('some' = 'var'); echo Value is $ar['some']; //syntax error echo Value is {$ar['some']}; //Value is var 28
  • 30. MULTIPLE ISSET $val = null; $var = true; if (isset($not_defined) isset($val) isset($var)) { /* ... */ } 30
  • 31. MULTIPLE ISSET if (isset($not_defined) isset($val) isset($var)) { /* ... */ } === if (isset($not_defined, $val, $var)) { /* ... */ } 31
  • 33. FILTER_INPUT $action = isset($_POST['action']) ? some_validate($_POST['action']) : 'default_action'; 33
  • 35. FILTER_INPUT /* data actually came from POST $_POST = array( 'product_id' = 'libgdscript', 'component' = '10', 'versions' = '2.0.33', 'testscalar' = array('2', '23', '10', '12'), 'testarray' = '2', ); */ $args = array( 'product_id' = FILTER_SANITIZE_ENCODED, 'component' = array( 'filter' = FILTER_VALIDATE_INT, 'flags' = FILTER_REQUIRE_ARRAY, 'options' = array('min_range' = 1, 'max_range' = 10) ), 'versions' = FILTER_SANITIZE_ENCODED, 'doesnotexist' = FILTER_VALIDATE_INT, 'testscalar' = array( 'filter' = FILTER_VALIDATE_INT, 'flags' = FILTER_REQUIRE_SCALAR, ), 'testarray' = array( 'filter' = FILTER_VALIDATE_INT, 'flags' = FILTER_REQUIRE_ARRAY, ) ); $myinputs = filter_input_array(INPUT_POST, $args); 35
  • 37. STRING CONCATENATION TIME F OR R IDDLE! 37
  • 38. STRING CONCATENATION WHO K NOWS W HAT'S T HAT? 38
  • 39. STRING CONCATENATION WHO K NOWS W HAT'S T HAT? 39
  • 40. STRING CONCATENATION CORRECT! 40
  • 42. STRING CONCATENATION $a = 'scissors'; $b = 'paper'; $c = 'rock'; $d = 'lizard'; $e = 'Spock'; $rules = $a . ' cut ' . $b . ', ' . $b . ' covers ' . $c . ', ' . $c . ' crushes ' . $d . ', ' . $d . ' poisons ' . $e . '...'; echo $rules; //scissors cut paper, paper covers rock, rock crushes lizard, lizard poisons Spock... 42
  • 43. STRING CONCATENATION $a = 'scissors'; $b = 'paper'; $c = 'rock'; $d = 'lizard'; $e = 'Spock'; $rules = $a cut $b, $b covers $c, $c crushes $d, $d poisons $e...; echo $rules; //scissors cut paper, paper covers rock, rock crushes lizard, lizard poisons Spock... 43
  • 44. STRING CONCATENATION $a = 'scissors'; $b = 'paper'; $c = 'rock'; $d = 'lizard'; $e = 'Spock'; $rules = %s cut %s, %s covers %s, %s crushes %s, %s poisons %s...; echo sprintf($rules, $a, $b, $b, $c, $c, $d, $d, $e); echo vsprintf($rules, array($a, $b, $b, $c, $c, $d, $d, $e)); printf($rules, $a, $b, $b, $c, $c, $d, $d, $e); vprintf($rules, array($a, $b, $b, $c, $c, $d, $d, $e)); //4x scissors cut paper, paper covers rock, rock crushes lizard, lizard poisons Spock... 44
  • 45. STRING CONCATENATION WHY U SE P RINTF FAMILY F UNCTIONS, WHEN W E H AVE S TRING INTERPOLATION? 45
  • 46. STRING CONCATENATION STRING PATTERN REUSE (CONNECTION STRINGS, API CALLS, ETC.) 46
  • 47. STRING CONCATENATION LOT OF FORMATTING OPTIONS 47
  • 49. QUICK OBJECT DEFINITION $obj = new stdClass(); $obj-foo = 123; $obj-bar = 'some'; //or (btw. not recursive!) $obj = (object)array('foo' = 123, 'bar' = 'some'); // unfortunately - not possible :( $obj = {'foo' = 123} 49
  • 51. ENUM class Roles { const ADMIN = 1; const USER = 2; const GUEST = 3; } $class = new ReflectionClass('Roles'); var_dump($class-getConstants()); /* array(3) { [ADMIN]= int(1) [USER]= int(2) [GUEST]= int(3) }*/ 51
  • 52. SPL FTW! 52
  • 55. DATE/TIME MANIPULATION + OBJECT/PROCEDURAL + TIMEZONES + INTERVALS + SOME OPERATORS + PHP CORE SINCE 5.2 55
  • 56. DATE/TIME MANIPULATION $a = new DateTime('2011-12-12'); $b = new DateTime('2011-11-12'); $c = new DateTime('2011-12-12'); var_dump(($a $b)); // false var_dump(($a $b)); // true var_dump(($c == $a)); // true // works $a-add(new DateInterval('P2D')); echo $a-format('Y-m-d') // echo 2011-12-14 // dont work :( $a += new DateInterval('P2D'); 56
  • 57. DID YOU MEAN ... 57
  • 58. DID YOU MEAN ... 58
  • 59. DID YOU MEAN ... YOU CAN TRY: http://php.net/manual/en/ function.levenshtein.php 59
  • 62. PARSING URL PARAMS parse_url $url = 'http://username:password@hostname/path?arg=value#anchor'; print_r(parse_url($url)); echo parse_url($url, PHP_URL_PATH); //and others, same as pathinfo /*Array ( [scheme] = http [host] = hostname [user] = username [pass] = password [path] = /path [query] = arg=value [fragment] = anchor ) /path */ 62
  • 63. PARSING URL PARAMS parse_str parse_str('single=Singlecheck[]=check1check[]=fooradio=radio2', $data); print_r($data);die(); /*Array ( [single] = Single [check] = Array ( [0] = check1 [1] = foo ) [radio] = radio2 ) */ 63
  • 64. PARSING URL PARAMS parse_str parse_str('single=Singlecheck[]=check1check[]=fooradio=radio2', $data); print_r($data);die(); /*Array ( [single] = Single [check] = Array ( [0] = check1 [1] = foo ) DOn'tusewithoutsecondparameter! [radio] = radio2 ) */ 64
  • 65. PARSING URL PARAMS parse_str function foo() { parse_str('single=Singlecheck[]=check1check[]=fooradio=radio2'); print_r(get_defined_vars());die(); } foo(); Localmagicvariables! 65
  • 67. CSV PARSING fgetcsv + str_getcsv 67
  • 68. CSV PARSING fgetcsv (for big files) $row = 1; if (($handle = fopen(test.csv, r)) !== FALSE) { while (($data = fgetcsv($handle, 1000, ,)) !== FALSE) { $num = count($data); echo p $num fields in line $row: br //pn; $row++; for ($c=0; $c $num; $c++) { echo $data[$c] . br /n; } } fclose($handle); } ? 68
  • 69. CSV PARSING str_getcsv (for smaller ones) $line = 'AddDescription My description to the file. filename.jpg'; $parsed = str_getcsv( $line, # Input line ' ', # Delimiter '', # Enclosure '' # Escape char ); var_dump( $parsed ); 69
  • 71. AUTO_PREPEND_FILE php.ini auto_prepend_file string Specifies the name of a file that is automatically parsed before the main file. The file is included as if it was called with the require()function, so include_path is used. The special value none disables auto-prepending. 71
  • 72. AUTO_PREPEND_FILE php.ini auto_prepend_file string Specifies the name of a file that is automatically parsed before the main file. The file is included as if it was called with the require()function, so include_path is used. The special value none disables auto-prepending. Greatplaceforyourawesomemydie,dump, debug,pukeetc.functions. Butbecarefulwhendeploying. 72
  • 74. FILE INCLUDE //config.php $dbName = 'some'; $dbPass = 'foo'; $dpPort = 123; //index.php include 'config.php'; echo $dbPass; //echo 'some' 74
  • 75. FILE INCLUDE //config.php $dbName = 'some'; $dbPass = 'foo'; $dpPort = 123; magicvariable! Local //index.php include 'config.php'; echo $dbPass; //echo 'some' 75
  • 76. FILE INCLUDE //config.php return array( 'dbName' = 'some', 'dbPass' = 'foo', 'dbPort' = 123 ); //index.php $config = include 'config.php'; echo $dbPass; //Notice 'undefined' echo $config['dbName'] = 'some'; 76
  • 77. FILE INCLUDE BTW. T HIS A LSO W ORKS //function.php return function($data) { print_r($data);die(); }; //index.php $dump = include 'function.php'; $dump(array(hello, 'moto')); 77
  • 79. QUICK COMMENT function foo() { $items = array(); foreach (array('some', 'a') as $item) { if ($item === 'a') { continue; } $items[] = $item; } return $items; } 79
  • 80. QUICK COMMENT function foo() { $items = array(); /* foreach (array('some', 'a') as $item) { if ($item === 'a') { continue; } $items[] = $item; } */ return $items; } 80
  • 81. QUICK COMMENT function foo() { $items = array(); /* */ foreach (array('some', 'a') as $item) { if ($item === 'a') { continue; } $items[] = $item; } /* */ return $items; } 81
  • 82. QUICK COMMENT function foo() { $items = array(); /* * foreach (array('some', 'a') as $item) { if ($item === 'a') { continue; } $items[] = $item; } /* */ return $items; } 82
  • 83. QUICK COMMENT function foo() { $items = array(); /* * foreach (array('some', 'a') as $item) { if ($item === 'a') { Anotheroptionsalsopossible continue; } $items[] = $item; } /* */ return $items; } 83
  • 84. ONE LINE VARIABLE SWAP 84
  • 85. ONE LINE VARIABLE SWAP $a = 123; $b = 987; list($a, $b) = array($b, $a); echo $a; //987 echo $b; //123 //or $a ^= $b ^= $a ^= $b; //http://betterexplained.com/articles/swap-two-variables-using-xor/ 85
  • 87. COMPACT + EXTRACT function index() { $user = Users::find(1); $items = Items::getAllForUser($user); return $this-render('index.twig', array( 'user' = $user, 'items' = $items )); //same as return $this-render('index.twig', compact('user', 'items')); } 87
  • 88. COMPACT + EXTRACT function foo() { $data = array('some' = 'asa', 'foo' = 'asda'); extract($data); var_dump(get_defined_vars());die(); } foo(); 88
  • 89. COMPACT + EXTRACT function foo() { $data = array('some' = 'asa', 'foo' = 'asda'); extract($data); var_dump(get_defined_vars());die(); } foo(); Onceagainlocalmagicvariables! 89
  • 90. FIRST ARRAY ELEMENT WITH ASSOCIATIVE KEYS 90
  • 91. FIRST ARRAY ELEMENT $data = array( 'foo' = 123, 'bar' = 1987, 'wee' = 'ugh' ); //echo $data[0]; //undefined offset echo reset($data); //123 echo current($data); //123 reset($data); list(,$value) = each($data); echo $value; //123 list($value) = array_values($data); echo $value; //123 echo array_shift($data); //123 - caution - modifies array //solution? echo array_shift(array_values($data)); //123 without modifying array 91
  • 93. RANDOM ARRAY ITEM $data = array( 'foo' = 123, 'bar' = 1987, 'wee' = 'ugh' ); // not like that - works only for number indexed arrays without gaps ! $random = $data[rand(0, count($data) - 1)]; // or that way - array_rand returns key, not value! $random = array_rand($data); // that way - works always $random = $data[array_rand($data)]; 93
  • 95. MULTIPLE VALUE CHECK $person = 'Barney'; if ($person == 'Joey' || $person == 'Rachel' || $person == 'Ross' || $person == 'Phoebe' || $person == 'Monica' || $person == 'Chandler' ) { echo 'Best comedy show ever'; } else if ($person == 'Barney' || $person == 'Ted' || $person == 'Lily' || $person == 'Marshal' || $person == 'Robin' ) { echo 'Copy of best comedy show ever, but still good one'; } else { echo 'Maybe another good show'; } 95
  • 96. MULTIPLE VALUE CHECK $person = 'Barney'; switch ($person) { case 'Joey': case 'Rachel': case 'Ross': /* ... */ echo 'Best comedy show ever'; break; case 'Barney'; case 'Ted'; /* ... */ echo 'Like a copy of best show ever, but still good one'; break; default: echo 'Maybe another good show'; } 96
  • 97. MULTIPLE VALUE CHECK $person = 'Barney'; if (in_array($person, array('Joey', 'Rachel', 'Ross', 'Phoebe', 'Monica', 'Chandler'))) ) { echo 'Best comedy show ever'; } else if (in_array($person, array('Barney', 'Ted', 'Lily', 'Marshal', 'Robin'))) ) { echo 'Like a copy of best comedy show ever, but still good one'; } else { echo 'Maybe another good show'; } 97
  • 98. MULTIPLE VALUE CHECK BTW! in_array($needle, $haystack) works like '==' in_array($needle, $haystack, true) works like '===' 98
  • 100. EMPTY ARRAY CHECK $input = array(); //it will work if (is_array($input) count($input) === 0) { } //via @wookiebpl if ($input === array()) { } 100
  • 101. EMPTY ARRAY CHECK //why not '=='? if ($input == array()) { } 101
  • 104. INNER ARRAYS OPERATIONS $shopCartPrices = array( 1 = 123.12, 4 = 23.34, 6 = 99.23 ); //sum? basic stuff. $sum = array_sum($shopCartPrices); 104
  • 105. INNER ARRAYS OPERATIONS BUT SOMETIMES... 105
  • 108. INNER ARRAYS OPERATIONS $shopCartPrices = array( 1 = array( 'price' = 123.12 ), 4 = array( 'price' = 23.34 ), 6 = array( 'price' = 99.23 ) ); //sure. you can do that $sum = 0; foreach ($shopCartPrices as $cartItem) { $sum += $cartItem['price']; } 108
  • 109. INNER ARRAYS OPERATIONS $shopCartPrices = array( 1 = array( 'price' = 123.12 ), 4 = array( 'price' = 23.34 ), 6 = array( 'price' = 99.23 ) ); //but you can do better = PHP = 5.3 $sum = array_sum(array_map(function($cartItem) { return $cartItem['price']; }, $shopCartPrices)); 109
  • 110. INNER ARRAYS OPERATIONS BUT W ITH T HIS O NE, P EOPLE OFTEN L OOK A T M E L IKE SOMEONE W HO'S U SING M AGIC. 110
  • 111. INNER ARRAYS OPERATIONS OR F ORCE 111
  • 112. INNER ARRAYS OPERATIONS $shopCartPrices = array( 1 = array( 'price' = 123.12 ), 4 = array( 'price' = 23.34 ), 6 = array( 'price' = 99.23 ) ); //and sometimes, even better - without PHP 5.3 $sum = array_sum(array_map('array_pop', $shopCartPrices)); 112
  • 113. LAST R IDDLE 113
  • 114. $var = 'a'; for($i = 0; $i 150; $i++) { $var++; echo $var, ' '; } //output? 114
  • 115. $var = 'a'; for($i = 0; $i 150; $i++) { $var++; echo $var, ' '; } //output? //b c d e f g h i j k l m n o p q r s t u v w x y z aa ab ac ad ae af ag ah ai aj ak al am an ao ap aq ar as at au av aw ax ay az ba bb bc bd be bf bg bh bi bj bk bl bm bn bo bp bq br bs bt bu bv bw bx by bz ca cb cc cd ce cf cg ch ci cj ck cl cm cn co cp cq cr cs ct cu cv cw cx cy cz da db dc dd de df dg dh di dj dk dl dm dn do dp dq dr ds dt du dv dw dx dy dz ea eb ec ed ee ef eg eh ei ej ek el em en eo ep eq er es et eu 115
  • 116. IT'S N OT A B UG. IT'S A F EATURE : ] 116
  • 117. 117