PHP - Cheatsheet

By xngo on March 17, 2019

Execution

php -f your_php_file.php

String

<?php
 
//***** String functions ****//
    // Extract id between parentheses.
    $str = "Hello (523)";
    $start_pos = strpos($str, "(")+1;
    $end_pos = strpos($str, ")");
    $id = substr($str, $start_pos, $end_pos-$start_pos);
    printf("id=%s", $id);
 
    //strpos($str, 'substr'): Find the position of the first occurrence of a substring in a string
    //strrpos($str, 'substr'): Find the position of the last occurrence of a substring in a string
 
//***** String formatting ****//
    $symbol='AAPL'; $name='Apple'; $nid=1231;
    echo sprintf("%s - %s (%s)", $symbol, $name, $nid);
    echo sprintf("two percent(%s%%)", '2');
 
    //number_format(double number[, int precision
    //              [, string decimal_separator, string thousands_separator]]);
    $number=7234.3432
    number_format($number, 2); // 7,234.34
 
?>   

Array

<?php
//***** Array ****//
    // Array size.
    $my_array=array(1,1,2);
    if (sizeof($my_array)==0)
        print("Empty arrary");
    else
        print("Array size=".sizeof($my_array));
 
    // Splitting array
    $big_array=array(1,2,4,5,6,7,8,9,10,11,12,13,14,15);
    foreach(array_chunk($big_array, 2) as $small_array)
        print_r($small_array);
 
    // Join elements of an array into 1 string.
    implode(",", $my_array);
    // Split string into an array.
    $my_array = explode(",", $str);
 
    // Append to array.
    $my_array [] = "new value";
    array_push($my_array,"value 1","value 2");
 
    // Insert element from array.
    $my_array = array('a', 'b', 'c', 'd', 'e');
    $inserted = array( 'x' ); // not necessarily an array.
 
    array_splice( $my_array, 3, 0, $inserted ); // splice in at position 3
    print_r($my_array); // $my_array is now a b c x d e
 
    // Remove element from array.
    unset($my_array[3]);    // unset will not re-index array keys.
    print_r($my_array);     // Position 3 is missing.
 
    // array_splice($arr, $pos, $len) will re-index array keys.
    $my_array = ['aa' => "a1", 'bb' => "b1", 'cc' => "c1"];
    array_splice($my_array, 0, 1); // Remove 'aa'=>"a1"
 
    // Search
    $my_array = ['aa' => "a1", 'bb' => "b1", 'cc' => "c1"];
    $key=array_search('c1', $my_array);
    $pos=array_search($key, array_keys($my_array));
    print(sprintf("key=%s, pos=%s\n", $key, $pos));    
 
?>   

If-condition

$is_ok = false;
if(!$is_ok) {
    echo "Use of negation successful.";
}

Date

<?php    
 
//***** Date ****//
    print(date('Y-m-d_H.i.s_u')."\n");
    print(date('D F jS, Y', 1552930880)."\n");
 
    echo date('F jS, Y', strtotime('Monday next week 2019-03-31'))."\n";
 
    // First day of this year.
    echo date('F jS, Y', strtotime('1/1 0 year'))."\n";
 
    // Last day of this year.
    echo date('F jS, Y', strtotime('1/1 next year -1 day'))."\n";
 
?>

Class

<?php
 
// Class
class Person{
    private $name;
    private $age;
 
    function __construct($name, $age){
        $this->name=$name;
        $this->age=$age;
    }
 
    public function getName(){ return $this->name; }
    public function getAge(){ return $this->age; }
}
 
// Using class.
$person = new Person('joe', 33);
print($person->getName()."\n");
 
// Add object in array.
$my_array=array();
$my_array[] = $person;
print_r($my_array);
        /*
        Array
        (
            [0] => Person Object
                (
                    [name:Person:private] => joe
                    [age:Person:private] => 33
                )
 
        )
        */
 
$object = new stdClass();
$object->name = "My name";
$my_array[0] = $object;
print_r($my_array);
        /*
        Array
        (
            [0] => stdClass Object
                (
                    [name] => My name
                )
 
        )
        */
 
?>

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.