Dano Manion

PHP Notes

Comments

  • I did not know I could use # to comment out code like //. That is cool.

Strings

  • A better way to output strings with variables. This way you don’t have to do a bunch of escape characters and crap. Much cleaner.

    $string = <<< EOT
      In "$title" by $author has a score of $rating stars.
    EOT;
    

Arrays

  • PHP 5.4+ now supports JS style Array creation.

    $characters = ['Picard','Riker','Data'];
    $characters[] = 'Deanna'; // Adds another item to the array.
    $characters[] = 'Beverly';
      	
    print_r($characters); // Should print them all.
    echo $characters[1]; // Riker
      	
      
    // Assign Values, Associative Arrays.
    $planets = [
    	'Mercury' => 'Melt your face.',
    	'Venus' => 'Too hot.',
    	'Earth' => 'Just right!',
    	'Mars' => 'Too cold, but we\'ll probably live.'
    ];
      	
    echo $planets['Earth'];
      	
    // Note: in order to use this in a double-qouted string do ... 
      	
    echo "The planet Earth is {$descriptions['Earth']}"
    

Null Coalesce Operator (only in PHP 7.0)

$unit_cost = 0;

$wholesale_price = $unit_cost ?? $non_existent ?? 25;

echo $wholesale_price; 

Functions

  • Pass by Reference changes the actual value of the original variable.

    $number = 2;
      
    // This will actually change the value of the variable. 
    // If this was not passed by reference and instead passed by value, the orginal 
    // variable would not chanbe because it would be somewhat sandboxed.
    function doubleIt(&$num) {
    	$num *= 2;
    }
      	
    doubleIt($number);
      	
    echo $number; // 4 
    

Forms

  • Understanding the difference between POST and GET.
    • GET: Use for search, because information is exposed in the URL
    • POST: Use only with forms, emails and inserting records into a DB

Variable Variables

$key = 'name';
$$key = 'David';
$name = 'david';

$key = 'email';
$$key = [email protected]';
$email = [email protected]';

$age = 12;
$input = 'age';
echo $$input; // Prints 12

/// you can also do this `$$$input`; it's like an inception process (up & up & up)