PHP

General

Tools

News

See Also

  • Hack – A version of PHP written by Facebook.
  • HHVM – A PHP server meant to run Hack apps.

Know This

  • PHP code goes between delimiters: <?php and ?>
  • Output string: echo “My string”;
  • Concatenation: . (e.g. “Hello” . “!” gives “Hello!”)
  • All variables in PHP start with a $
  • Add a semicolon at the end of each statement.
  • x++ is shorthand for x+1
  • Comments: // or multi-line:  /* */
  • Comparison Operators:
    • >
    • <
    • <=
    • >= Greater than or equal to
    • == Equal to
    • != Not equal to
  • Conditional Statement:
    • If:
      • If (condition) { statement; }
    • Else:
      • If (condition) { statement; } else { statement; }
    • Else If:
      • If (condition) { statement; } elseif (condition) { statement } else { statement }
    • Switch:
      • switch (variable) { case 1: statement; break; case 2: statement; break; default: statement; }
  • Arrays
    • $array = array(“Blue”, “Orange”, “Green”);
    • Each item in an array is numbered, starting on the left with 0.
    • Use brackets to access an item at a specific position in an array, e.g. $array[1]
      • Alternatively one can use {}. e.g. $array{1}
    • To set an element in an array: $array[1] = newvalue
    • To remove an element from an array use unset: unset($array[1]).
  • Loops
    • For
      • for (start_of_loop; end_of_loop; increment_loop)
      • ex.: for (x=1; x<10; x++) { command; }
    • While
      • while (condition) { code }
      • ex.: while (x < 10) { x++; }
      • Alternatively, one can use while (cond): code endwhile;
    • Do While
      • Will execute at least once
      • do { code } while (condition);
      • ex.: do { x+1 } while (x < 1);
    • Foreach
      • foreach (list_of_items as item) { code }
      • foreach ($numbers as $item)  { echo $item; }

Functions

Operators

  • ? – ternary (aka conditional) operator
    • ex.: $param=isset($_GET[‘param’]) ? $_GET[‘param’] : ‘default’;
    • If the first parameter is true, use its result; otherwise if second is true; use its result; else use third.
    • Leaving out middle operand is supported in PHP 5.3+, middle operand above is “$_GET[‘param’]. Without middle operand looks like: $result = $x ?: ‘default’;
  • :: – scope resolution (aka paamayim nekudotayim) operator
    • Used when one wants to reference a specific instance of a function.

Terms

  • static
  • scope resolution operator

Old Code

Further Reading

%d bloggers like this: