PHP basics

  1. PHP in a nutshell
  2. Basic syntax
    1. Hello world
    2. Operators
    3. Declarations
    4. Functions
    5. Control structures
    6. Arrays
    7. Built in types
  3. Errors
    1. PHP Errors
    2. What is next?
This tutorial will show you basic PHP syntax and its features. If you’re new to PHP read the most basic PHP tutorial to get started as quickly and painlessly as possible. For becoming modern PHP developer read and follow also PHP: The Right Way. Seriously.

PHP in a nutshell

  • scripting language
  • procedural and object oriented language
  • dynamically (weakly) typed
  • syntax similar to C, C++, C#, Java and Perl
  • Imperative language
  • PHP has closures

Basic syntax

Hello world

File hello.php:


echo 'Hello, world.';
$ php hello.php

Operators

Arithmetic operators

OperatorNameResult
-$anegationOpposite of $a.
$a + $badditionSum of $a and $b.
$a - $bSubtractionDifference of $a and $b.
$a * $bMultiplicationProduct of $a and $b.
$a / $bdivisionQuotient of $a and $b.
$a % $bmodulusRemainder of $a divided by $b.
$a ** $bExponentiationResult of raising $a to the $b’th power.

Comparison operators

OperatorNameResult
$a == $bEqualTRUE if $a is equal to $b after type juggling.
$a === $bIdenticalTRUE if $a is equal to $b, and they are of the same type.
$a != $bNot equalTRUE if $a is not equal to $b after type juggling.
$a <> $bNot equalTRUE if $a is not equal to $b after type juggling.
$a !== $bNot identicalTRUE if $a is not equal to $b, or they are not of the same type.
$a < $bLess thanTRUE if $a is strictly less than $b.
$a > $bGreater thanTRUE if $a is strictly greater than $b.
$a <= $bLess than or equal toTRUE if $a is less than or equal to $b.
$a >= $bGreater than or equal toTRUE if $a is greater than or equal to $b.

Logical operators

OperatorNameResult
$a and $bAndTRUE if both $a and $b are TRUE.
$a or $bOrTRUE if either $a or $b is TRUE.
$a xor $bXorTRUE if either $a or $b is TRUE, but not both.
! $aNotTRUE if $a is not TRUE.
$a && $bAndTRUE if both $a and $b are TRUE.
$a || $bOrTRUE if either $a or $b is TRUE.

Assignment operators

OperatorDescription
=Set a value to variable
+=Addition of numeric value to variable
.=Add string to variable

Declarations

  • $i = 1; - assign value to variable
  • define('FOO', 'something'); - define a constant *

Functions

// a simple function
function functionName() {}

// function with parameters
function functionName($param1, $param2) {}

Anonymous functions (closures)


echo preg_replace_callback('~-([a-z])~', function ($match) {
    return strtoupper($match[1]);
}, 'hello-world');
// outputs helloWorld

// Anonymous function variable assignment example
$greet = function($name) {
    printf("Hello %s\r\n", $name);
};
$greet('World');

// inherit
$message = 'hello';

// Without "use" keyword
$example = function () {
    var_dump($message);
};
echo $example();

// Inherit $message
$example = function () use ($message) {
    var_dump($message);
};
echo $example();

Variadic functions


function sum(...$nums)
{
    return array_sum($nums);
}

Control structures

If

if $x > 0 {
    return $x;
} else {
    return -$x;
}

Loops

// for
for ($i = 1; $i<10 span="">; $i++) {}

// while
while ($i < 10) {}

// do while
$i = 0;
do {
    echo $i;
} while ($i > 0);


// foreach
foreach ($array as $key => $value) {}

Switch

// switch statement
switch ($operatingSystem) {
    case 'darwin':
        echo 'Mac OS Hipster';
        break;
    case 'linux':
        echo 'Linux Geek';
        break;
    default:
        // Windows, BSD, ...
        echo 'Other';
}

Arrays

$array = [
    "foo" => "bar",
    "bar" => "foo",
];

Operations on arrays

OperatorNameResult
$a + $bUnionUnion of $a and $b.
$a == $bEqualityTRUE if $a and $b have the same key/value pairs.
$a === $bIdentityTRUE if $a and $b have the same key/value pairs in the same order and of the same types.
$a != $bInequalityTRUE if $a is not equal to $b.
$a <> $bInequalityTRUE if $a is not equal to $b.
$a !== $bNon-identityTRUE if $a is not identical to $b.

Built-in types

Type
boolean
integer
float
string
array
object
resource
NULL

Errors

PHP errors


// Turn off all error reporting
error_reporting(0);

// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);

// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);

// Report all PHP errors (see changelog)
error_reporting(E_ALL);

// Report all PHP errors
error_reporting(-1);

// Same as error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);

Exceptions

function inverse($x) {
    if (!$x) {
        throw new Exception('Division by zero.');
    }
    return 1/$x;
}

try {
    echo inverse(5) . "\n";
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
} finally {
    echo "This is always executed.\n";
}

What is next?

Use php.net. It has a great and detailed manual for a lot of your PHP adventures.

No comments:

Post a Comment