overview edit doc new doc remove

Jan 26, 2018

PHP

PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML. PHP code is written between ""<?php ... ?>"" tags.

Basics

Syntax

Comments

/* 
  Multiline
  comment 
*/

// Single line comment

Quotes

Double Quotes print many escape sequences, the values for the variables and more. Single quotes print what is between them and ignore escape sequences except for * and \*.

Datatypes

The data is stored in an array which is named $_POST.

$usersName = $_POST['username'];
$streetAddress = $_POST['streetaddress'];
$cityAddress = $_POST['cityaddress'];

Local and global variable;

$str = "aa";
global $var2;

Constants:

define('PI', 3.1415926);

if else

$numOfOranges = 4;
$numOfBananas = 36;

if (($numOfOranges > 25) && ($numOfBananas > 30)) {

  echo '25% Discount';

} elseif (($numOfOranges > 30) || ($numOfBananas > 35)) {

  echo '15% Discount';

} elseif (!(($numOfOranges < 5)) || (!($numOfBananas < 5))) {

  echo '5% Discount';

} else {

  echo 'No Discount For You';

}

Loops

Switch
switch ($usersName) {

  case "Sally" :
  echo "Hello Sally";
  break;

  default :
  echo "Hello Valued Customer";
  break;      

}
While
$num = 0;
while ($num < 20) {

  echo ++$num . ', ';

}
For
for ($num = 1; $num <= 20; $num++) {

  echo $num;

  if ($num != 20) {

    echo ', ';

  } else {

    break; // or exit() to leave the whole script

  }
}
Foreach
foreach ($bestFriends as $friend) {

  echo $friend . ', ';

}

Casting

echo "</br>5 / 2 = " . (integer) (5 / 2);
echo "</br>5 % 2 = " . (5 % 2) . "</br></br>";

Random numbers

echo rand() . "\n";

Strings

You can trim white space with ltrim, rtrim, or trim.

echo strlen($randString) . "</br>";
echo strlen(ltrim($randString)) . "</br>";
echo strlen(rtrim($randString)) . "</br>";
echo strlen(trim($randString)) . "</br>";

Arrays

$bestFriends = array('Joy', 'Willow', 'Ivy');

Key value pairs

$customer = array('Name'=>$usersName, 'Street'=>$streetAddress, 'City'=>$cityAddress);

foreach ($customer as $key => $value) {

  echo $key . ' : ' . $value . '</br>';

}

Multidimensional arrays

$customers = array (array('abc', '123', '000'), array('def', '456', '222'),
             array ('ghi', '789', '333'));

for ($row = 0; $row < 3; $row++) {
  for ($col = 0; $col < 3; $col++) {

    echo $customers[$row][$col] . ', ';

  }

  echo '</br>';

}

Arrayfunctions

sort($yourArray) //Sorts in ascending alphabetical order
asort($yourArray) //sorts arrays with keys
ksort($yourArray) //sorts by the key

Functions

function addNumbers ($num1, $num2) {

  return $num1 + $num2;

}

echo "3 + 4 = " . addNumbers(3, 4);
1