PHP crash course

By xngo on March 6, 2019

Overview

This is intend for programmers. It shows the basic syntax of PHP language on 1 page.

String format

<?php
 
printf("%s\n", 'string');
printf("%-40s\n", 'left-justify');
 
printf("%.3f\n", 3.234141); // 3 decimal precision.
 
printf("%'.09d\n", 12345)   // Zero padding.
 
?>

Loop

<?php
$max=10;
for($i=0; $i<$max; $i++)
{
    $perc=rand(0,19)/1000;
    if(rand(0,10)%2==0)
        $perc=0.05+$perc;
    else
        $perc=0.05-$perc;
    print($perc." | ");
}
 
$my_array = array(2, 3);
foreach($my_array as $item){
    array_push($my_array, $item*2);
}
var_dump($my_array);
?>

Class

<?php
class Person
{
    var $name;
    var $age;
 
    function __construct($name, $age){
        $this->name = $name;
        $this->age = $age;
    }
 
    function getName(){
        return $this->name;
    }
 
    function getAge(){
        return $this->age;
    }
}
 
// Using Person class.
$person = new Person('John', 33); // Instantiate an object.
print($person->getName()); // Calling function.
 
?>

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.