PHP: Difference between revisions

From Wiki
Jump to navigation Jump to search
 
No edit summary
 
(2 intermediate revisions by the same user not shown)
Line 132: Line 132:
print strpos("abcdefgh", "de");            # 3
print strpos("abcdefgh", "de");            # 3
print str_replace("teh", "the", "In teh beginning...");
print str_replace("teh", "the", "In teh beginning...");
<source>
</source>


== Arrays ==
== Arrays ==

Latest revision as of 18:43, 28 April 2017

Manual

http://www.php.net/manual/en/

Example

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/2000/REC-xhtml1-20000126/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
   <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
   <title>Blank PHP Script</title>
</head>
<body>
<?php
echo "<h1>Here is a heading</h1>";
?>
</body>
</html>

Comments

# single line
// single line
/* multiple
   line */

Constants

define("PI", 3.14159); print PI;   # outputs 3.14159

Scalar Variables

# four scalar types: boolean, integer, float, string
$value = "Here is some text.";
$message = "Memory: {$memory}MB";  # curly braces separate variable from context

Conditional Expressions

# 0, "0", null, and unset are false, otherwise true
# conditional expressions evaluate the same way as Java
# === and !== test for equivalence of both value and type
("10 feet" == 10) but ("10 feet" !== 10)

Flow Control

if ($var > 5)
    print "Variable greater than 5";
elseif ($var < 0)
    print "Variable is negative.";
else {
    print "Variable is positive and less than or equal to 5";
    print "Here is some more text";
}
# switch, while, do while, and for loops are identical to Java
# use of break and continue is same as in Java

Type Casting

(bool), (int), (float), (string) to cast type
# gettype( ), print_r( ), and var_dump( ) give type information

Functions

function bold($string) {
    print "<b>" . $string . "</b>";
}
# static variable
function count( ) {
    static $count = 0;
    return $count++;
}
# pass by reference
function doublevalue(&$var) {
    $var = $var * 2;
}
# default parameter value
function heading($text, $headingLevel = 2){
    ...
}

Functions in include files

Here is functions.inc

function bold($string) {
    print "<b>" . $string . "</b>";
}

Here is how to use it:

include("functions.inc");   # warn if not found
require("functions.inc");   # error if not found

String Manipulation

$var = $var . " string";                   # concatenation (like Perl)
$length = strlen($my_string);              # string length
$words = explode(" ", "Now is the time");  # tokenize on space character
$array_string = implode(", ", $array);     # comma-separated values
printf("Result: %.2f\n", $pi);             # print formated to output buffer
$output = sprintf("Result: %.2f\n", $pi);  # return formatted string
print str_pad("PHP", 6);                   # prints "PHP   "
print strtolower("PHP and MySQL");         # php and mysql
print strtoupper("PHP and MySQL");         # PHP AND MYSQL
print ucfirst("now is the time");          # Now is the time
print ucwords("now is the time");          # Now Is The Time
print trim(" Tiger Land \n");              # "Tiger Land"
print ltrim(" Tiger Land \n");             # "Tiger Land \n"
print rtrim(" Tiger Land \n");             # " Tiger Land"
# string comparison
print strcmp("aardvark", "zebra");         # -1
print strcmp("zebra", "aardvark");         #  1
print strcmp("mouse", "mouse");            #  0
print strcmp("mouse", "Mouse");            #  1
print strncmp("aardvark", "aardwolf", 4);  #  0
print strncmp("aardvark", "aardwolf", 5);  # -1
print strcasecmp("mouse", "Mouse");        #  0
# substrings
print substr("abcdefgh", 2);               # "cdefgh"
print substr("abcdefgh", 2, 3);            # "cde"
print substr('abcdef', -1, 1);             # "f"
print substr("abcdefgh", -5, -2);          # "def"
print strpos("abcdefgh", "de");            # 3
print str_replace("teh", "the", "In teh beginning...");

Arrays

# array length
print count($array);
# keys are integers by default
$numbers = array(5, 4, 3, 2, 1);
print $numbers[2];       # prints 3
$words = array("Web", "Database", "Applications");
print $words[0];         # prints "Web"
$shopping = array( );    # create empty array
$shopping[] = "Milk";    # add elements to the end of the array
$shopping[] = "Coffee";
$shopping[] = "Sugar";
print "The first item in my list is {$shopping[0]}";  # use {} inside quotes
# strings can be used as keys, like a Perl hash
$array = array("first"=>1, "second"=>2, "third"=>3);
print $array["second"];  # prints "2"
# removing an element from an array with unset doesn't reassign keys
unset($words[1]);        # $words[2] is still "Applications"
unset($words);           # destroys entire array
# the values of an array can be arrays or objects, too
$planets = array(
    "Mercury"=> array("dist"=>0.39, "dia"=>0.38),
    "Venus"  => array("dist"=>0.72, "dia"=>0.95),
    "Earth"  => array("dist"=>1.0,  "dia"=>1.0,
                      "moons"=>array("Moon")),
    "Mars"   => array("dist"=>0.39, "dia"=>0.53,
                      "moons"=>array("Phobos", "Deimos"))
    );
print $planets["Earth"]["moons"][0];  # prints "Moon"
print "The {$planets2["Earth"]["moons"][0]} is a balloon";  # still need {}
# iterate over an array's values
foreach ($array as $value){
    # do something with $value
}
# iterate over an arrays key/value pairs
foreach ($array as $key => $value){
    # do something with key, value
}

Array Functions

# array size
print "array size: " . count($array); # prints number of elements
# value frequency
$pets = array("Beth"=>"Dog", "Arabella"=>"Rabbit", "Meg"=>"Cat", "Neda"=>"Cat");
$petFrequency = array_count_values($pets);
print_r($petFrequency);  # Array ( [Dog] => 1 [Rabbit] => 1 [Cat] => 2 )
# create an array with all the same values
$unity = array_fill(1, 10, "one");
# create an array with incremented values
$letters = range("A", "F");
# min, max values
$min = min($numbers); $max = max($numbers);
# true if haystack contains needle
if (in_array($needle, $haystack)) print "found it";
# find the key for a given value
$key = array_search($value, $array);  # return false if not found
# WARNING: the first element of an integer-key array will return 0.
# Distinguish this from boolean false using the === operator

# true if key exists
if (array_key_exists($key, $array)) print "found it";
# get a list of keys for an array
$keys = array_keys($array);
# get a list of values for an array
$values = array_values($array);
# strip out non-unique values from an array
$unique_values = array_unique($array);
# concatenate two arrays
$big_array = array_merge($array1, $array2);
# reverse the order of an array
$reversed = array_reverse($array);
# sort/reverse-sort the elements of an array (does not return a copy)
sort($array); rsort($array);
# sort/reverse-sort an associative array on values
asort($array); arsort($array);
# sort/reverse-sort an associative array on keys
ksort($array); krsort($array);
# sort with a user-defined comparison function
function length_compare($a, $b){
    if (strlen($a) < strlen($b)) return -1;
    if (strlen($a) > strlen($b)) return 1;
    return 0;
}
usort($array, "length_compare");  # sort by values, assign new indices
uasort($array, "length_compare"); # sort by values, keep old keys
uksort($array, "length_compare"); # sort by keys, keep old values

Regular Expressions

$found = ereg('\.com', "www.ora.com");      # true
$found = ereg("[ABC][123]", "A1 Quality");  # true
$found = ereg("[^0-9a-zA-Z]", "123abc");    # false
# eregi is same as ereg but case insensitive
$valid_email = eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email);    
# Perl-based regular expression matching
$found = preg_match('\.com', "www.ora.com");  # true

Dates and Times

print time( );                           # 1064699133 (seconds since 1/1/1970)
$aDate = mktime(8, 15, 0, 6, 23, 1972);  # 8:15am on 6/23/1972 (local time)
$var = strtotime("25 December 2002");
$var = strtotime("14/5/1955");
$var = strtotime("Fri, 7 Sep 2001 10:28:07 -1000");
print strtotime("+1 day");               # tomorrow
print strtotime("-2 weeks");             # two weeks ago
print strtotime("+2 hours 2 seconds");   # in two hours and two seconds
print date('d/m/Y', $date);              # "24/08/1974"
print date('m/d/y', $var);               # "08/24/74"
$valid = checkdate(1, 1, 1066);          # true
$valid = checkdate(1, 1, 2929);          # true
$valid = checkdate(13, 1, 1996);         # false
$valid = checkdate(4, 31, 2001);         # false
$valid = checkdate(2, 29, 1996);         # true
$valid = checkdate(2, 29, 2001);         # false

Math

Just as in perl or java.

File I/O

$filename = "/home/paul/test.txt";      # unix
$filename = "c:\\paul\\test\\test.txt"; # windows
# dump a file to the screen
if (!@readfile($filename)) {   # '@' supresses error output to screen
    print "Could not open $filename.\n";
}
# read file to a string, complete with newline characters
$filestring = file_get_contents($filename);
if ($filestring) {
    print $filestring;
} else {
    print "Could not open $filename.\n";
}
# read file into an array
$filearray = file($filename);
if ($filearray) {
    while (list($var, $val) = each($filearray)) {
        ++$var;
        $val = trim($val);
        print "Line $var: $val<br />";
    }
} else {
    print "Could not open $filename.\n";
}
# write a string to a file (PHP < 5)
function file_write_string($file, $string){
    $fh = fopen($file, "wb");
    $string .= "\n";
    fwrite($fh, $string);
    fclose($fh);
}
# append a string to a file (PHP < 5)
function file_append_string($file, $string){
    $fh = fopen($file, "ab");
    $string .= "\n";
    fwrite($fh, $string);
    fclose($fh);
}
# write an array/string to a file (PHP >= 5)
$numbytes = file_put_contents($filename, $mydata);  # mydata is string or array
print "$numbytes bytes written\n";
# append to a file (PHP >= 5)
$numbytes = file_put_contents($filename, $mydata, FILE_APPEND);
# rename/move a file
$filename2 = $filename . '.old';
$result = rename($filename, $filename2);
# copy a file
$filename2 = $filename . '.old';
$result = copy($filename, $filename2);
# delete a file
$result = unlink($filename);
# check for existence
$result = file_exists($filename);
# filename deconstruction
$fileinfo = pathinfo($filename);  # array contains dirname, basename, extension

Form Processing

Example form:

<form action="process.php" method="post">
<select name="item">
<option>Paint</option>
<option>Brushes</option>
<option>Erasers</option>
</select>
Quantity: <input name="quantity" type="text" />
<input type="submit" />
</form>

process.php:

$quantity = $_POST['quantity'];
$item = $_POST['item'];
echo "You ordered ". $quantity . " " . $item . ".<br />";

Sending Email

$status = mail('barney@somehost.com', 'About your message', $message);

Redirect

<?php
header( 'Location: http://www.yoursite.com/new_page.html' ) ;
?>

Debugging

# to write the error stream to the web page, edit php.ini to include this:
display_errors = On
# WARNING: this should be Off in a production site

# to see server settings:
print phpinfo();

print_r($variable);   # shows keys and values
var_dump($variable);  # shows keys, values, and types