PHP programming - Basic Elements
Frank Yap

In this section we will look at the PHP type juggling, string operations and array manipulations.
 
Resources

 
Lab Exercises

 
Exercise 1: Understand PHP type juggling

Understand the following PHP type juggling.
 

$var;
var_dump($var);     // Code error will trigger an error display. See section "Debugging PHP" for debug mode control. Notice: Undefined variable: var, Error caused by uninitialized var.
NULL  
 
$var = "";
var_dump($var); string(0) ""
 
$var = 0;
var_dump($var); int(0)
 
$var = 23;
var_dump($var); int(23)
 
$var = 023;
var_dump($var); int(19) The 023 is an octal number in PHP.
 
 
$var = 08;
var_dump($var); int(0) The 8 is not in the range of octal (0-7) so the number is treated as a string!
 
 
$var = (int)"08";
var_dump($var); int(8)
 
$var = 1 + "4Flowers";
var_dump($var); int(5)
 
$var = (bool)"0Tree";
var_dump($var); bool(true)
 
$var = (bool)(false);
var_dump($var); bool(false)
 
$var = (bool)"false";
var_dump($var); bool(true)
 

 

Exercise 2: String operations

Study variable expansions in double quoted, single quoted, HEREDOC and NOWDOC strings.
 

Variable expansion in strings
 
$fruits = "oranges"; 
$str = "We should not compare apples and $fruits."; 
echo $str . "<br>"; 
$str = 'We should not compare apples and $fruits.'; 
echo $str . "<br>";
Output ---
We should not compare apples and oranges.
We should not compare apples and $fruits.
 
Variables are expanded within double quotes.
Variables are not expanded within single quotes.
Single quotes are slightly faster.
Variables are expanded within heredoc strings.
Variables are not expanded within nowdoc strings.
 


HEREDOC and NOWDOC string examples.
 

Displaying HTML tags.
 
The following code shows how to display HTML code including tags.
Use NOWDOC to capture HTML code and display using the following functions.
Detailed manual for NOWDOC is available here http://php.net/manual/en/language.types.string.php.
 
<?php 
function dispHtmlTags ($strHtml) { 
$strHtml = htmlentities ($strHtml); // performs escaping operations 
$strHtml = str_replace ("\r\n", "&nbsp;<br>", $strHtml); // &nbsp; added to avoid IE bug 
$strHtml = str_replace ("\n", "&nbsp;<br>", $strHtml);  
echo "<pre>$strHtml</pre>"; 

 
function dispHtmlTagsAttr ($strHtml, $tagAndAttr) { // pass tagAndAttr without angle brackets 
$strHtml = htmlentities ($strHtml); // performs escaping operations 
$strHtml = str_replace ("\r\n", "&nbsp;<br>", $strHtml); // &nbsp; added to avoid IE bug 
$strHtml = str_replace ("\n", "&nbsp;<br>", $strHtml); 
$pos = strpos ($tagAndAttr, ' '); 
$endTag = substr ($tagAndAttr, 0, $pos); 
echo "<pre><$tagAndAttr>$strHtml</$endTag></pre>"; 

?>
 
Capture HTML string using NOWDOC.
<?php 
$strHtml = <<<'strMark' 
<!DOCTYPE html> 
<html lang="en"> 
<head> 
<title>PHP Lab</title> 
</head> 
<body> 
<div> 
<h2>Simple HTML page</h2> 
</div> 
<div> 
<?php echo "<h1> Hello World! </h1>"; ?> 
</div> 
</body> 
</html> 
strMark; // end mark should start at 1st column and no character after ';' 
 
dispHtmlTagsAttr ($strHtml, "pre class='code'"); // display HTML code 
?>
 


String examples where HEREDOC is used.
 

Source code
 
<?php 
$var = 'Hello!'; 
 
$strHtml = <<<strMark 
<?php 
$var = (bool)"false"; 
var_dump($var); 
?> 
strMark; 
 
dispHtmlTagsAttr ($strHtml, "pre class='code'"); 
?>
 
Source code displayed on screen
 
<?php 
Hello! = (bool)"false"; 
var_dump(Hello!); 
?>
 
In the above HEREDOC string all occurrences of $var are replaced with "Hello!".
This example shows HEREDOC could result in unexpected error. Unless you need to expand variables, it is safer to use NOWDOC.
NOWDOC however is available only PHP version 5.3 or later and if you have to display source code with HEREDOC you can still do that by escaping $ characters in the string.
 
Example:
 
<?php 
$var = 'Hello!'; 
 
$strHtml = <<<strMark 
<?php 
\$var = (bool)"false"; 
var_dump(\$var); 
?> 
strMark; 
 
dispHtmlTagsAttr ($strHtml, "pre class='code'"); 
?>
 

 

Exercise 3: Adding or deleting elements in array

Study adding or deleting elements in array.
 

Merging arrays
 
$beginning = 'foo'; 
$end = array(1 => 'bar'); 
$result = array_merge((array)$beginning, (array)$end); 
print_r($result);
Output ---
Array
(
    [0] => foo
    [1] => bar
)
 
 
Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one.
It returns the resulting array.
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one.
If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array.
array_merge() only accepts parameters of type array. However, you can use typecasting to merge other types.
 


Slicing arrays
 
$input = array("a", "b", "c", "d", "e"); 
 
$output = array_slice($input, 2); // returns "c", "d", and "e" 
$output = array_slice($input, -2, 1); // returns "d" 
$output = array_slice($input, 0, 3); // returns "a", "b", and "c" 
 
// note the differences in the array keys 
print_r(array_slice($input, 2, -1)); 
print_r(array_slice($input, 2, -1, true));
Output ---
Array
(
    [0] => c
    [1] => d
)
Array
(
    [2] => c
    [3] => d
)
 
 
Function definition:
array array_slice ( array $array , int $offset [, int $length = NULL [, bool $preserve_keys = false ]] )
 
If offset is non-negative, the sequence will start at that offset in the array. If offset is negative, the sequence will start that far from the end of the array.
 
If length is given and is positive, then the sequence will have up to that many elements in it. If the array is shorter than the length, then only the available array elements will be present. If length is given and is negative then the sequence will stop that many elements from the end of the array. If it is omitted, then the sequence will have everything from offset up until the end of the array.
 
Note that array_slice() will reorder and reset the numeric array indices by default. You can change this behaviour by setting preserve_keys to TRUE.
 


Appending arrays
 
<?php 
$stack = array("orange", "banana"); 
array_push($stack, "apple", "raspberry"); 
print_r($stack); 
?>
Output ---
Array
(
    [0] => orange
    [1] => banana
    [2] => apple
    [3] => raspberry
)
 
 
array_push() appends one or more elements onto the end of an array.
 
Alternate methods:
Using $arr[]     // faster method
Using array_merge()
 


Removing last element of an array
 
<?php 
$stack = array("orange", "banana", "apple", "raspberry"); 
$fruit = array_pop($stack); 
print_r($stack); 
?>
Output ---
Array
(
    [0] => orange
    [1] => banana
    [2] => apple
)
 
 
array_pop() removes the element off the end of array.
 
Alternate method:
Using array_slice()
 


Removing first element of an array
 
<?php 
Array = array("orange", "banana", "apple", "raspberry"); 
raspberry = array_shift(Array); 
print_r(Array); 
?>
Output ---
Array
(
    [0] => banana
    [1] => apple
    [2] => raspberry
)
 
 
array_shift() removes the first element of an array.
 
Alternate method:
Using array_slice()
 


Prepending elements into an array
 
<?php 
$queue = array("orange", "banana"); 
array_unshift($queue, "apple", "raspberry"); 
print_r($queue); 
?>
Output ---
Array
(
    [0] => apple
    [1] => raspberry
    [2] => orange
    [3] => banana
)
 
 
array_unshift() prepends elements to an array.
 
Alternate method:
Using array_merge()
 
 
Homework Exercise

1. Start XAMPP Apache server.
2. Create an HTML frame in a php file and add a paragraph introducing yourself and echo the whole code so that the code is displayed exactly as you have written (tags have to be displayed).
3. Using a browser display the page you created.
4. Verify that the display is as you intended.