Contents
Objectives
To learn to use several PHP functions useful for Web application development.
To learn to write and use your own functions – a prelude to writing your own classes.
Using Some Basic PHP Functions
We examine several other useful functions including some basic numeric PHP functions, e.g.,
abs() Function
The absolute value function takes a single numerical argument and returns its absolute value. For example,
$x=abs(- 5);
$y=abs(42);
print "x=$x y=$y";
Will output x=5 y=42
sqrt()
The square root function takes a single numerical argument and returns its square root. For example,
$x= sqrt(25);
$y= sqrt(24);
print "x=$x y=$y";
Will output x=5 y=4.898979485566
round()
The round function with 1 numerical argument returns the number rounded to the nearest integer. E.g.,
$x=round( - 5.456);
$y=round(3.7342);
print "x=$x y=$y";
Will output x=-5 y=4
A 2nd argument can define the number of digits after the decimal point to round to. E.g.,
$x=round( - 5.456,2);
$y=round(3.7342,3);
print "x=$x y=$y";
would output x=-5.46 y=3.734
is_numeric()
is_numeric () is useful for determining whether a variable contains a valid number or a numeric string. It returns true in this case and false otherwise, e.g.,
if (is_numeric($input)) {
print "Valid number:$input";
} else {
print "Not a valid number:$input";
}
If $input == "6"
, the output would be Valid number:6
If $input == "Happy"
the output would be Not a valid number:Happy
Testing for data types
The following functions test for different data types and return true if the variable contains data of the specified type.
- is_ array(…),
- is_ bool(…),
- is_ callable(…),
- is_ double(…),
- is_ float(…),
- is_ int(…),
- is_ integer(…),
- is_ long(…),
- is_ null(…),
- is_ object(…),
- is_ real(…),
- is_ resource(…),
- is_ scalar(…),
- is_ string(…).
The function string gettype(…) can be used to return the data type as a string.
rand() and srand()
The function rand() returns (pseudo)random numbers. The function srand() is used to seed the random function. Using a different seed each time the random number generator is used the first time in a program is a good way of getting a different sequence of random numbers for each program run. If the same seed is used for each run if the program, then the same sequence of numbers will be output by the random number generator, hence the term pseudo-random number generator.
Use srand() and microtime() to seed rand() and ensure it returns a random number, for example,
srand ((double) microtime () * 10000000);
$dice = rand(1, 6);
print "Your random dice toss is $dice";
The random number generated in this case can be a 1, 2, 3, 4, 5, or 6.
print, echo, and quotation marks
You don’t need to use parentheses with print(), much like echo.
Double quotes are used to delimit strings that will be parsed for variables to substitute. Therefore,
$x = 10;
print ("Mom, please send $x dollars.");
will output Mom, please send 10 dollars.
Single quotes delimit string literals that will not be parsed. Therefore,
$x = 10;
print ('Mom, please send $x dollars.');
will output Mom, please send $x dollars.
You also need double quotation marks to generate special escaped characters like \n, \r, etc.
$str = "Hi, Mom! \n"; //has an end of line
$str2 = 'Hi, Mom! \n'; //has the characters \n
echo nl2br($str); //will output an HTML <br> at the end of the string
echo nl2br($str2); //will not output an HTML <br>
The nl2br
function converts newline characters to the HTML <br> element. In the case on line 4, it does not output this element, because $str2
does not contain a newline character.
Generating HTML elements
Using single or double quotation statements can be useful when generating HTML tags print ‘<font color=”blue”>’;
This above is easier to understand and actually runs slightly faster than using all double quotation marks and the backslash ( \ ) character : print “<font color= \”blue \”>”;
Function syntax
Use the following syntax to write functions. Include parentheses at the end of the function name to hold the parameter list.
function_name () {
…
}
The following function takes 2 arguments:
function OutputTableRow($c1, $c2) {
print "<tr><td>$c1</td><td>$c2</td></tr>";
}
Consider the following code …
<html>
<head>
<title> Simple Table Function</title>
</head>
<body>
<font color="blue" size=4>
<table border=1>
<?php
function OutputTableRow( $col1, $col2 ) {
print "<tr><td>$col1</td><td>$col2</td></tr>";
}
for ( $i=1; $i<=4; $i++ ) {
$message1="Row $i Col 2";
$message2="Row $i Col 2";
OutputTableRow($message1, $message2);
}
?>
</table>
</body>
</html>
Returning Values
Your functions can return data to the calling script. Your functions can return the results of a computation, the status of a process, etc. You can use the PHP return statement to return a value to the calling script statement:
return $result;
This variable’s value will be returned to the calling script. For example
function getMax ( $num1, $num2 ) {
// PURPOSE: returns largest of 2 numbers
// ARGUMENTS: $num1 - 1st number, $num2 - 2nd number
return ($num1 > $num2?$num1:$num2);
}
Using External Script Files
Sometime you will want to use scripts from external files, functions and classes from libraries. PHP supports 4 related functions:
require("header.php");
include("trailer.php");
require_once("header.php");
include_once("trailer.php");
The require()
function produces a fatal error if it can’t insert the specified file. The include()
function produces a warning if it can’t insert the file. Ensure inclusion/requiring is done only once by using the require_once
or include_once
respectively instead.
These search for the file named within the string parameter and insert its PHP, HTML, or JavaScript code into the current file.
For example, might use the following as footer.php.
<hr><p>123 Elm, Montreal, Qc, H0H0H0 - 514-555-5555</p>
Can include using: <?php include("footer.php"); ?>
Sequential Arrays
Use the array()
function or []
to create an array.
$students = array('Johnson', 'Jones', 'Jackson', 'Jefferson');
$grades = [66, 75, 85, 80];
Another way to create an array You can also create an array by making individual value assignments into the array variable name. E.g.,
$students[] = 'Johnson';
$students[] = 'Jones';
$students[] = 'Jackson';
$students[] = 'Jefferson';
To reference individual array items, use an array name and index pair.
$sports[0] = 'baseball';
$names = array('Alice', 'Bob', 'Carol', 'Dennis');
echo "$names[0], $names[1], $names[2], $names[3]";
By default sequential arrays start with index 0, e.g., the fourth element has index 3. Avoid referencing an item past the end of your array (for example, using $names[20] in an array that contains only four items).
Array indices can be whole numbers or a variable.
$i =3;
$classes = array('Math', 'History', 'Science', 'Pottery');
$oneclass = $classes[$i - 1];
print "$classes[$i] $oneclass $classes[1] $classes[0]";
This code outputs Pottery Science History Math
Changing arrays values: You can change values in an array as follows:
$scores = array(75, 65, 85, 90);
$scores[3] = 95;
$average = ($scores[0] + $scores[1] + $scores[2] + $scores[3]) / 4;
print "average=$average";
The output of the above PHP segment is average=80
.
Explicitly-Set Indices
Below, we assign the value of 65 to the item with index 2, 85 to index 1.
$scores = array(1=>75, 2=>65, 3=>85);
$scores[] = 100;
print "$scores[1] $scores[2] $scores[3] $scores[4]";
Assign the value of 85 to the item with index 3. Add item with value 100 to the end of the array. The above outputs 75 65 85 100
.
Loops and Sequential Arrays
Looping statements can be used to iterate through arrays
$courses = array ('Perl', 'PHP', ' C','Java ', 'Pascal', 'Cobol', 'Visual Basic');
for ($i=0; $i < count($courses); $i++) {
echo "$courses[$i] ";
}
The above repeats 7 times, with $i equal to 0, 1, 2, 3, 4, 5, and 6. The above outputs: Perl PHP C Java Pascal Cobol Visual Basic
.
The foreach loop
PHP supports the foreach statement as another way to iterate through arrays.
$courses = array('Perl', 'PHP', 'C', ' Java','Pascal ', 'Cobol', 'Visual Basic');
foreach ($courses as $item){
print ("$item ");
}
The above outputs Perl PHP C Java Pascal Cobol Visual Basic
.
Sorting data
For example the following code segment outputs1 11 55 91 99 119 911
.
$courses = array (91, 55, 11, 1, 99, 911, 119);
sort($courses);
foreach ($courses as $item) {
print "$item ";
}
Arrays and User Input
Consider an example script that enables end-user to select multiple items from a checklist. Suppose the form inputs are generated as follows:
<form action='' method='post'>
<?php
$topics = ['animals', 'cars', 'cooking', 'furniture'];
foreach($topics as $topic){
echo "<input type='checkbox' name='pref[]' value='$topic' />$topic";
}
?>
...
</form>
Suppose you are receiving the previous form as follows:
$pref = $_POST["prefer"];
If the user selected the second and fourth checkbox items on the previous form, then $pref[]
would be an array of two items:
- $pref[0], would have a value of
cars
, and - $pref[1] would have a value of
furniture
.
Adding and Deleting Items
- array_shift() removes an item from the beginning of an array.
- array_pop() removes an item from the end of an array.
- array_unshift() adds an item to the beginning of an array.
- array_push() adds an item to the end of an array.
Useful Array Functions
Use max() and min() to find the largest and smallest number in an array.
$grades = array (99, 100, 55, 91, 65, 22, 16);
$big=max($grades);
$small=min($grades);
print "max=$big min=$small";
The above would output: max=100 min=16
.
Use array_sum () to return a sum of all numerical values. For example,
$grades = array (25, 100, 50, 'N/A');
$total= array_sum ($grades);
print "Total=$total";
The above would output: Total=175
PHP will try to convert character to numerical values when it can. For example,
$grades = array ('2 nights', '3days', 50, '1 more day');
$total=array_sum($grades);
print "total=$total";
Instead of generating an error message, this code outputs total=56
.
Associative Arrays
PHP also supports arrays with string – value indices called associative arrays. For example, the following code creates an associative array with three items.
$instructor['Science'] = 'Smith';
$instructor['Math'] = 'Jones';
$instructor['English'] = 'Jackson';
Use the array()
function or []
along with the => operator to create an associative array, e.g.,
$months = array( 'Jan'=>31, 'Feb'=>28, 'Mar'=>31, 'Apr'=>30, 'May'=>31, 'Jun'=>30, 'Jul'=>31, 'Aug'=>31, 'Sep'=>30, 'Oct'=>31, 'Nov'=>30, 'Dec'=>31 );
Use syntax similar to sequential arrays to access items: Enclose the index in square brackets.
$days = $months['Mar'];
Note that you can’t fetch indices by using data values, as in the following example:
$mon = $months[28]; //no can do
This syntax is incorrect because associative arrays can fetch data values only by using indices (not the other way around). This is the case for all arrays…
Multidimensional lists
Some data is best represented using a list of list or a multidimensional list, e.g.,
$inventory=array (
'AC1000'=>array('Part'=>'Hammer', 'Count'=>122, 'Price'=>12.50),
'AC1001'=>array('Part'=>'Wrench', 'Count'=>5, 'Price'=>5.00),
'AC1002'=>array('Part'=>'Hand Saw', 'Count'=>10, 'Price'=>10.00),
'AC1003'=>array('Part'=>'Screw Driver', 'Count'=>222, 'Price'=>3.00)
);
$inventory[‘AC1000’][‘Part’] has the value Hammer, $inventory[‘AC1001’][‘Count’] has the value 5, and $inventory[‘AC1002’][‘Price’] has the value 10.00.