PHP Cheat Sheet

From Project Encycode

Jump to: navigation, search

Contents

[edit] Program Structure

[edit] HTML Embedding

All PHP statements should be embedded inside the HTML as shown.

<HTML>
<HEAD>PHP Sample</HEAD>
<BODY>
<?php
    print "Welcome to PHP";
?>
</BODY>
</HTML>

[edit] Functions

function functionName( arg1, arg2, arg3){
 
  statement list
  return $somevalue;
 
}

Functions with default parameters

function functionName( arg1, arg2, arg3=123){
 
  statement list
  return $somevalue;
 
}


[edit] Variables

Variables in PHP are loosely typed and need not be declared before using them. Variables in PHP are always preceded with a $ sign.

[edit] Variable Variable names

Variable Variable name is a variable name which can be set and used dynamically.

$vara = 'ValueA';
$varb = 'ValueB';
$varname = 'vara'
echo "$varname $$varname";

The above code outputs 'vara ValueA'


[edit] PHP Comments

// Single line comment
# Another way of single line comment
/*  
  Multi line 
   comments
*/

[edit] DataTypes

PHP variables can contain values of any of the following data types without any explicit declaration. The variable behaves according to the datatype it contains.

Datatype Description
Integers Whole numbers equivalent in range to C compiler's long data type
Floating-Point Numbers Floating-point numbers or real numbers equivalent to C compiler's double data type.
Strings Sequence of characters. Can be represented in three different ways, double quoted strings, single quoted strings and Here-Docs.
Booleans Boolean value can be either true or false (Introduced in PHP 4).
Null Datatype with only one possible value, the NULL value. Indicates the variable is empty.
Resources A special datatype that represents a PHP extension resource such as a database connection, open file etc.
Arrays Collection of key/value pairs. The keys(indexes) can be either integers or strings whereas values can be of any type including arrays.


[edit] Operators

[edit] Arithmetic Operators

Operator Description
+ Addition
- Substraction
* Multiplication
/ Division
 % Modulus (Division Remainder)
++ Increment
-- Decrement

[edit] Comparison Operators

Operator Description
== equality
 != inequality
< is less than
> is greater than
<= is less than or equal to
>= is greater than or equal to
=== Identical to. Same as ==, but the types also need to match.
 !== True if either the value or the type is different.

[edit] Logical Operators

Operator Description
| | (no space inbetween), or Logical OR
&&, and Logical AND
xor Logical XOR
 ! Logical NOT

[edit] Bitwise Operators

Operator Description
| Bitwise OR
& Bitwise AND
^ Bitwise XOR
~ Bitwise Negation

[edit] Other Operators

Operator Description
. Concatenates two strings. Any non-string operand is converted to a string.
= Assignment operator. Assigns the value of the variable on the right to the variable on the left
=& By-reference Assignment. Assigns the reference to the variable on right to the variable on the left.
@ Silence operator. Silences any error messages during the evaluation of the expression.
 ?: Ternary operator used for condition assignment.
+= Short addition operator. $a += $b; is eqal to $a = $a + $b;
-= Short subtraction operator. $a -= $b; is eqal to $a = $a - $b;
*= Short multiplication operator. $a *= $b; is eqal to $a = $a * $b;
/= Short division operator. $a /= $b; is eqal to $a = $a / $b;
 %= Short modulo operator. $a %= $b; is eqal to $a = $a % $b;

[edit] Flow of Control

[edit] Conditionals

[edit] If Statement

Statement

if (expr)
    statement
elseif (expr)
    statement
elseif (expr)
    statement
    ...
else
    statement

Statement List

if (expr):
    statement list
elseif (expr):
    statement list
elseif (expr):
    statement list
    ...
else:
    statement list
endif;

[edit] Switch Statement

switch (expr){
    case expr:
        statement list
        break;
    case expr:
        statement list
        break;
    default:
        statement list
        break;
}

[edit] Loops

[edit] For Loop

Statement

for (startexpr; conditionexpr; incrementexpr)
    statement

Statement List

for (startexpr; conditionexpr; incrementexpr):
    statement list
endfor;

[edit] Foreach Loop

foreach ($array as $val)
    statement
foreach ($array as $key => $val)
    statement

Statement List

foreach ($array as $val)
    statement
endforeach;

[edit] While Loop

Statement

while (expr)
    statement

Statement List

while (expr):
    statement list
endwhile;

[edit] Do While Loop

do {
    statement list
} while (false)

[edit] Break Statement

Break out of inner loop.

break;

Break out from n innermost loops.

break n;

[edit] Continue Statement

Continues executing the next interation of the innermost loop.

continue;

Continues executing the next interation of the nth innermost loop.

continue n;


[edit] Operations

[edit] isset()

isset determines whether a certain variable has already been declared by PHP. It returns a boolean value true if the variable has already been set, and false if it is not set or set to the value NULL.

if (isset($var)) {
    print 'Value for var is already set';
}

[edit] unset()

unset undeclares a previously set variable, and frees any memory that was used by it if no other variable references its value.

unset($var));

[edit] empty()

Empty determines whether a variable is empty.

if (empty($var))) {
    print 'Variable var is empty';
}

[edit] Language Specifics

[edit] Superglobals

PHP doesn't support global varibles, but certain internal variables behave like global variables. These are called superglobals.

Variable Description
$_GET[] An array that includes all the GET variables that PHP received from the client browser
$_POST[] An array that includes all the POST variables that PHP received from the client browser
$_COOKIE[] An array that includes all the cookies that PHP received from the client browser.
$_ENV[] An array with the environment variables.
$_SERVER[] An array with the values of the web-server variables.


[edit] Traversing Arrays using list and each

while (list($key, $val) = each($arrayvar)) {
    print "Key=$key, Value=$val";
}

[edit] Code Inclusion Control Structures

[edit] include

When an include statement is executed, PHP reads the file, compiles into intermediate code, and then executes the included code. Unlike C/C++ include statements behaves like a function that can even return a value using return statement.

include filename

[edit] eval

Eval accepts the code as a string, compiles, executes and returns the result value.

$a = 4;
print eval('$a*4');

[edit] PHP5 OO Language

[edit] Class

class MyClass {
 
    //Constructor
    function __construct(params...)
    {
        //construction code
    }
 
    //Destructor
    function __destruct()
    {
        //destruction code
    }
 
    //Properties
    private $prop1;
    private $prop2;
 
    //Static properties
    static $staticVar1;
 
    //Functions...
    function fun1($param1,...)
    {
    }
 
    //Static Functions
    static function statfun1($param1,...)
    {
    }
 
    //Constants
    const BLACK = "Black";
 
}

[edit] Interface

interface MyIntf {
    function intfFun1($param1,...);
}

[edit] instanceOf Operator

$obj instanceOf Shape

[edit] Abstract Class and Functions

abstract class MyAbsClass
{
    //Abstract function
    abstract function absFun1($param1,...);
 
}

[edit] Inheritance

Implementing one ore more interfaces

class MyClass implements I1, I2,...
{
    .....
}

Extending interfaces

interface NewIntf extends I1, I2,...
{
    .....
}


Extending Class

class MyClass2 extends MyClass1
{
    .....
}

[edit] Final

Final Classes

final class MyFinalClass
{
    .....
}

Final Methods

class MyClass
{
    final function myFinalFunc($param1,...)
    {
        ....
    }
}
Personal tools