PHP—Functions

Functions generally take some type of input and return some type of output (although, sometimes either input or output can be omitted). Here are examples of some PHP mathematical functions:


$a = 5.4;
$b = round( $a ); // rounds $a to nearest integer; $b equals 5

$a = 5.4;
$b = floor( $a ); // rounds down to nearest integer; $b again equals 5

$a = 5.4;
$b = ceil( $a ); // rounds up; $b equals 6

$r = rand( 1, 100 ); // $r becomes a random number from 1 to 100

$a = 9;
$root = sqrt( $a ); // square root:  $root = 3

$big = pow( 2, 30 ); // power; $big = 2 raised to the 30th power

Here are samples of three control functions:


//
// The header function sends an HTML header to the browser; the
// following example redirects a browser:
header( "Location: http://cs-people.bu.edu/stevec" );
exit;

//
// Use the exit command after the header function to stop the
// execution of your current PHP.  Note that, to work, the header
// function must be the first thing sent to the browser (before
// any echo commands).
//

//
// The mail function sends an e-mail:
mail( "jsmith@cs.bu.edu", "Web Page", "Another hit!",
      "From: jsmith@cs.bu.edu" );

//
// In this case, the mail is to jsmith, from jsmith.  Note, the
// line return and spacing between "Another hit!," and
// "From: jsmith@cs.bu.edu" is just for readability and has no
// effect on the program.

Finally, here is a function that gets the time and date:


$time = date("g:i:sA"); // the g is replaced with the hour,
                        // the i with the minute, the s with
                        // the second, and the A with "AM" or
                        // "PM"
$hour = date("g");
$ampm = date("A");
$today = date("l, F j, Y"); // the l becomes the day of the week; // the F, the month; the j, the day; and // the Y, the year

Next (Getting Variables From Forms)