´╗┐Table of Contents

PHP

What is php?

PHP is a scripting language run on a server to build dynamic web pages. The scripts are saved in files on the server with extension ".php". Scripting languages are one form of programming languages which are mainly used to automate tasks. They are interpreted by a software rather than compiled into machine language. Originally, PHP stood for Personal Home Page, but it would rather stands for Hypertext Pre-Processor.

On a web server, PHP generates HTML webpages. However, it is used for many programming tasks in addition to web page generation and dynamic web tasks.

PHP code can be embedded in an HTML document, or it may be used in a php script document. PHP files can contain text, HTML, CSS, JavaScript, and PHP code. PHP generates also images, pdf files and videos.

Delimiters

PHP code has to be enclosed in delimiters: <?php ....; ?>

<?php
    echo 'Hello, World!';
?>

Case Sensitivity

keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined functions are not case-sensitive. so, echo or ECHO is the same. However; all variable names are case-sensitive!

Comments

single line comment starts with two forward slashes or "#" multi-line comment starts with forward slash asterisk and ends with asterisk forward slash.

// This is a comment;
# This is also a comment;
/* This is 
Multiline comment
.....................
...................
*/

Variables

A variable starts with the $ sign, followed by the name of the variable which is case sensitive. Variables are not declared. Interpreter would know which type is the variable. String variables are quoted. Variable names can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ), although they should not start with a number.

Scopes

A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function, not inside functions, which have their LOCAL SCOPE. A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function, not in any other function or outside it.

To access a LOCAL variable outside its function you have to declare it GLOBAL :

<?php
$x = 5;
$y = 10;

function myFunc() {
  global $x, $y;
  $y = $x + $y;
}

myFunc();
echo $y; // outputs 15
?>

All global variables in an array called $GLOBALS[index]. The index holds the name of the variable.

A LOCAL variable inside a function is deleted once the function is executed. If you want to reuse, as in the case of loop execution of the function, you need to declare as static variable.

<?php
function myTest() {
  static $x = 0;
  echo $x;
  $x++;
}
?>

Display Output

Echo and print statements are similar. * echo has no return value while print has a return value of 1 * echo can take multiple parameters while print can take one argument. The text argument can contain HTML markup in both cases. Variables have to given outside quoted text.

<?php
$txt1 = "Hello World"
echo "<h2>" . $txt1 . "</h2>";
echo "First statement in computing is  " . $txt2 . "<br>";
?>

DATA TYPES

A string is a sequence of characters inside single or double quotes. An integer is non-decimal number. A float (floating point number) is a number with a decimal point. A Boolean represents two possible states: TRUE or FALSE. An Array stores multiple values in one single variable. An Object stores data and information on how to process that data. A Class contains methods and their attributes (properties).

<?php
class Car {
  function Car() {
    $this->model = "VW";
  }
}

// create an object
$herbie = new Car();

// show object properties
echo $herbie->model;
?>

String Functions

  • strlen(str) function returns the length of a string.
  • str_word_count(str) function counts the number of words in a string.
  • strrev(str) function reverses a string.
  • strpos(string, string_pattern) function searches for a specific text within a string. If a match is found, the function returns the character position of the first match. If no match is found, it will return FALSE.
  • str_replace(word, replacement, string) function replaces some characters with some other characters in a string.
  • addcslashes() Returns a string with backslashes in front of the specified characters
  • addslashes() Returns a string with backslashes in front of predefined characters
  • bin2hex() Converts a string of ASCII characters to hexadecimal values
  • chop() Removes whitespace or other characters from the right end of a string
  • chr() Returns a character from a specified ASCII value
  • chunk_split() Splits a string into a series of smaller parts
  • convert_cyr_string() Converts a string from one Cyrillic character-set to another
  • convert_uudecode() Decodes a uuencoded string
  • convert_uuencode() Encodes a string using the uuencode algorithm
  • count_chars() Returns information about characters used in a string
  • crc32() Calculates a 32-bit CRC for a string
  • crypt() One-way string hashing
  • echo() Outputs one or more strings
  • explode() Breaks a string into an array
  • fprintf() Writes a formatted string to a specified output stream
  • get_html_translation_table() Returns the translation table used by htmlspecialchars() and htmlentities()
  • hebrev() Converts Hebrew text to visual text
  • hebrevc() Converts Hebrew text to visual text and new lines (\n) into
  • hex2bin() Converts a string of hexadecimal values to ASCII characters
  • html_entity_decode() Converts HTML entities to characters
  • htmlentities() Converts characters to HTML entities
  • htmlspecialchars_decode() Converts some predefined HTML entities to characters
  • htmlspecialchars() Converts some predefined characters to HTML entities
  • implode() Returns a string from the elements of an array
  • join() Alias of implode()
  • lcfirst() Converts the first character of a string to lowercase
  • levenshtein() Returns the Levenshtein distance between two strings
  • localeconv() Returns locale numeric and monetary formatting information
  • ltrim() Removes whitespace or other characters from the left side of a string
  • md5() Calculates the MD5 hash of a string
  • md5_file() Calculates the MD5 hash of a file
  • metaphone() Calculates the metaphone key of a string
  • money_format() Returns a string formatted as a currency string
  • nl_langinfo() Returns specific local information
  • nl2br() Inserts HTML line breaks in front of each newline in a string
  • number_format() Formats a number with grouped thousands
  • ord() Returns the ASCII value of the first character of a string
  • parse_str() Parses a query string into variables
  • print() Outputs one or more strings
  • printf() Outputs a formatted string
  • quoted_printable_decode() Converts a quoted-printable string to an 8-bit string
  • quoted_printable_encode() Converts an 8-bit string to a quoted printable string
  • quotemeta() Quotes meta characters
  • rtrim() Removes whitespace or other characters from the right side of a string
  • setlocale() Sets locale information
  • sha1() Calculates the SHA-1 hash of a string
  • sha1_file() Calculates the SHA-1 hash of a file
  • similar_text() Calculates the similarity between two strings
  • soundex() Calculates the soundex key of a string
  • sprintf() Writes a formatted string to a variable
  • sscanf() Parses input from a string according to a format
  • str_getcsv() Parses a CSV string into an array
  • str_ireplace() Replaces some characters in a string (case-insensitive)
  • str_pad() Pads a string to a new length
  • str_repeat() Repeats a string a specified number of times
  • str_replace() Replaces some characters in a string (case-sensitive)
  • str_rot13() Performs the ROT13 encoding on a string
  • str_shuffle() Randomly shuffles all characters in a string
  • str_split() Splits a string into an array
  • str_word_count() Count the number of words in a string
  • strcasecmp() Compares two strings (case-insensitive)
  • strchr() Finds the first occurrence of a string inside another string (alias of strstr())
  • strcmp() Compares two strings (case-sensitive)
  • strcoll() Compares two strings (locale based string comparison)
  • strcspn() Returns the number of characters found in a string before any part of some specified characters are found
  • strip_tags() Strips HTML and PHP tags from a string
  • stripcslashes() Unquotes a string quoted with addcslashes()
  • stripslashes() Unquotes a string quoted with addslashes()
  • stripos() Returns the position of the first occurrence of a string inside another string (case-insensitive)
  • stristr() Finds the first occurrence of a string inside another string (case-insensitive)
  • strlen() Returns the length of a string
  • strnatcasecmp() Compares two strings using a "natural order" algorithm (case-insensitive)
  • strnatcmp() Compares two strings using a "natural order" algorithm (case-sensitive)
  • strncasecmp() String comparison of the first n characters (case-insensitive)
  • strncmp() String comparison of the first n characters (case-sensitive)
  • strpbrk() Searches a string for any of a set of characters
  • strpos() Returns the position of the first occurrence of a string inside another string (case-sensitive)
  • strrchr() Finds the last occurrence of a string inside another string
  • strrev() Reverses a string
  • strripos() Finds the position of the last occurrence of a string inside another string (case-insensitive)
  • strrpos() Finds the position of the last occurrence of a string inside another string (case-sensitive)
  • strspn() Returns the number of characters found in a string that contains only characters from a specified charlist
  • strstr() Finds the first occurrence of a string inside another string (case-sensitive)
  • strtok() Splits a string into smaller strings
  • strtolower() Converts a string to lowercase letters
  • strtoupper() Converts a string to uppercase letters
  • strtr() Translates certain characters in a string
  • substr() Returns a part of a string
  • substr_compare() Compares two strings from a specified start position (binary safe and optionally case-sensitive)
  • substr_count() Counts the number of times a substring occurs in a string
  • substr_replace() Replaces a part of a string with another string
  • trim() Removes whitespace or other characters from both sides of a string
  • ucfirst() Converts the first character of a string to uppercase
  • ucwords() Converts the first character of each word in a string to uppercase
  • vfprintf() Writes a formatted string to a specified output stream
  • vprintf() Outputs a formatted string
  • vsprintf() Writes a formatted string to a variable
  • wordwrap() Wraps a string to a given number of characters

CONSTANTS

Constants are fixed variables which can not be changed once defined. Constants are automatically global across the entire script.

//syntax : define(name, value, case-insensitive)
<?php
define("GREETING", "Hello World!", true);
echo greeting;
?>

You can create a CONSTANT ARRAY which will be GLOBAL:

<?php
define("cars", [
  "Alfa Romeo",
  "BMW",
  "Toyota"
]);
echo cars[0];
?>

Conditional Statements

Conditional statements are used to perform different actions based on different conditions.

  • if statement
  • if...else statement
  • if...elseif
  • switch statement
if (condition) {
  code to be executed if this condition is true;
} elseif (condition) {
  code to be executed if first condition is false and this condition is true;
} else {
  code to be executed if all conditions are false;
}
switch (n) {
  case label1:
    code to be executed if n=label1;
    break;
  case label2:
    code to be executed if n=label2;
    break;
  case label3:
    code to be executed if n=label3;
    break;
    ...
  default:
    code to be executed if n is different from all labels;
}

LOOPS

Loops are used to execute the same block of code again and again, as long as a certain condition is true. * while (true) * do...while : repeats the loop while true * for : loops a specified number of times * foreach : loops for each element in an array

FUNCTIONS

PHP has over 1000 built-in functions that can be called directly, from within a script. A user-defined function declaration starts with the word function. Function names are NOT case-sensitive. To call the function, just write its name followed by brackets ().

function functionName() {
  code to be executed;
}

Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.

function myFamily($fname, $fage) {
  echo "$fname is $fage years old.<br>";
}
myFamily("Sam", "23")

To let a function return a value, use the return statement.

ARRAYS

An array is a special variable, which can hold more than one value at a time.

  • Indexed arrays - Arrays with a numeric index
  • Associative arrays - Arrays with named keys
  • Multidimensional arrays - Arrays containing one or more arrays

Indexed Arrays

In indexed arrays, the index is created automatically and it starts with 0. You loop through indexed array using for loop:

<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);

for($x = 0; $x < $arrlength; $x++) {
  echo $cars[$x];
  echo "<br>";
}
?>

Associative arrays

Associative arrays are arrays that use named keys as an index. The named keys can then be used in a script:

<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>

To loop through associative array :

<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

foreach($age as $x => $x_value) {
  echo "Key=" . $x . ", Value=" . $x_value;
  echo "<br>";
}
?>

Multidimensional Arrays

$cars = array (
  array("Volvo",22,18),
  array("BMW",15,13),
  array("Saab",5,2),
  array("Land Rover",17,15)
);

Include other scripts

The include (or require) statement takes all the text/code/markup that exists in the specified file and copies it into the file that uses the include statement.