Logo

* Most of the material is taken from this online course.
<?php
  echo '<p>Hello World!</p>'; // this is a comment                      
  phpinfo(); # this is also a comment. Multi-line comments with /* */
  error_reporting(E_ALL);
  ini_set("display_errors", 1);
  $a = 4;  # variables have $
  echo "value of a is:".$a  # dot is the string concatenation operator
?>

Arrays

- An array in PHP is actually an ordered map. It can be treated as a list, dictionary and more.
- An array can be created as
array(
  key1 => value1,
  key2 => value2,
  key3 => value3,
  ...
)

- As of PHP 5.4, we can use [] instead of array().
- The key can either be an integer or a string.
- In the keys, Floats, Bools and Strings containing valid decimal integers are cast to integers.
- Same keys overwrite previous ones.
$array = array(
    1    => "a",
    "1"  => "b",
    1.5  => "c",
    true => "d",
);
print_r($array);  # Array ( [1] => d )
var_dump$array);  # array(1) { [1]=> string(1) "d" } 

- The key is optional. If it is not specified, PHP will use the increment of the largest previously used integer key.
- To change a certain value, assign a new value to that element using its key (like list or dict in Python).
- To delete element from array use unset():
$arr = array(5 => 1, 12 => 2, 17 => 6);
unset($arr[5])  # This removes the first element of array.
unset($arr)  # This deletes the whole array

- To reindex after deletting an entry, use array_values().
- The foreach control structure exists specifically for arrays and objects:
$arr = [1, 3, 5, 7];
foreach ($arr as $key => $value) {  # If we don't need the key, we can write '$arr as $value'
  ...
}

- Changing the values of an array directly is possible by passing them by reference :
$colors = ['red', 'blue', 'green', 'yellow'];
foreach ($colors as &$color) {  # '&' is used to pass by reference.
    $color = strtoupper($color);
}
unset($color); /* ensuring that following writes to $color
                  will not modify the last array element. */

- Array assignment always involves value copying. Use assignment by reference to change both items involved:
$arr1 = [2, 3];
$arr2 = $arr1;
$arr2[0] = 4; # $arr2 is changed to [4, 3],
              # $arr1 is still [2, 3]
             
$arr3 = &$arr1;
$arr3[0] = 4; // now $arr1 and $arr3 are the same

Strings

  • strpos() is a built-in function which searches a string for another string and returns the position of the string. -->

Input

# fill an array with all items from a directory
$handle = opendir('.');
while (false !== ($file = readdir($handle))) {
  $files[] = $file;
}
closedir($handle); 
print_r($files);

Functions

function ($arg1, ...) {}
  ...;
  return ...;
}

For a global variable we can use either global (like python), or GLOBALS (The $GLOBALS array is an associative array with the name of the global variable being the key and the contents of that variable being the value of the array element):
$a = 1;
function sum_a($b) {
  global $a;
  return $a + $b;
}
$a = 1;
function sum_a($b) {
  return $GLOBALS['a'] + $b;
}

A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope:
 function test() {
  static $a = 0;
  echo $a;
  $a++;
}

Now, $a is initialized only in first call of function and every time the test() function is called it will print the value of $a and increment it.
Static declarations are resolved in compile-time.

Forms

<form action="action.php" method="post">
  <p>Your name: <input type="text" name="name" /></p>
  <p>Your age: <input type="text" name="age" /></p>
  <p><input type="submit" value="Submit!" /></p>
</form>    

Then we need an action.php page to show the page that appears after pressing submit button:
Hi <?php echo htmlspecialchars($_POST['name']); ?>. 
# htmlspecialchars is to avoid injecting HTML tags or javascript into the page
You are <?php echo (int)$_POST['age']; ?> years old.
# (int) conversion gets rid of any stray characters.

To use an image as the submit button:
<input type="image" src="image.gif" name="sub" />

When the user clicks somewhere on the image, the accompanying form will be transmitted to the server with two additional variables, sub_x and sub_y. These contain the coordinates of the user click within the image.

Misc.

  • <?= 'testing echo with =' ?> is equivalent to <?php 'testing echo with =' ?>.
  • Unlike the double-quoted and heredoc syntaxes ("<<<EOD"), variables and escape sequences for special characters will not be expanded when they occur in single quoted strings or nowdocs("<<<'EOD'").
  • inside a double-quoted string, it's valid to not surround array indexes with quotes so "$foo[bar]" is valid.
  • The type of a variable is not usually set by the programmer; rather, it is decided at runtime by PHP depending on the context in which that variable is used.