Contoh-Contoh Script PHP
Contoh-Contoh Script PHP
<?php
// get current date and time
$now = getdate();
// turn it into strings
$currentTime = $now["hours"] . ":" . $now["minutes"] .∝
":" . $now["seconds"];
$currentDate = $now["mday"] . "." . $now["mon"] . "." . $now["year"];
// result: "It is now 12:37:47 on 30.10.2006" (example)
echo "It is now $currentTime on $currentDate";
?>
Formatting Timestamps
<?php
// get date
// result: "30 Oct 2006" (example)
echo date("d M Y", mktime()) . " \n";
// get time
// result: "12:38:26 PM" (example)
echo date("h:i:s A", mktime()) . " \n";
// get date and time
// result: "Monday, 30 October 2006, 12:38:26 PM" (example)
echo date ("l, d F Y, h:i:s A", mktime()) . " \n";
// get time with timezone
// result: "12:38:26 PM UTC"
echo date ("h:i:s A T", mktime()) . " \n";
// get date and time in ISO8601 format
// result: "2006-10-30T12:38:26+00:00"
echo date ("c", mktime());
?>
Comparing Dates
<?php
// create timestamps for two dates
$date1 = mktime(0,0,0,2,1,2007);
$date2 = mktime(1,0,0,2,1,2007);
// compare timestamps
// to see which represents an earlier date
if ($date1 > $date2) {
$str = date ("d-M-Y H:i:s", $date2) . " comes before " .∝
date ("d-M-Y H:i:s", $date1);
} else if ($date2 > $date1) {
$str = date ("d-M-Y H:i:s", $date1) . " comes before " .∝
date ("d-M-Y H:i:s", $date2);
} else {
$str = "Dates are equal";
}
// result: "01-Feb-2007 00:00:00 comes before 01-Feb-2007 01:00:00"
echo $str;
?>
Printing Arrays
<?php
// define array
$data = array(
"UK" => array(
"longname" => "United Kingdom", "currency" => "GBP"),
"US" => array(
"longname" => "United States of America", "currency" => ∝
"USD"), "IN" => array(
"longname" => "India", "currency" => "INR"));
// print array contents
print_r($data);
var_dump($data);
?>
Processing Arrays
<?php
// define indexed array
$idxArr = array("John", "Joe", "Harry", "Sally", "Mona");
// process and print array elements one by one
// result: "John | Joe | Harry | Sally | Mona | "
foreach ($idxArr as $i) {
print "$i | ";
}
?>
<?php
// define associative array
$assocArr = array("UK" => "London", "US" => "Washington",∝
"FR" => "Paris", "IN" => "Delhi");
// process and print array elements one by one
// result: "UK: London US: Washington FR: Paris IN: Delhi "
foreach ($assocArr as $key=>$value) {
print "$key: $value";
print "<br />";
}
?>
Processing Nested Arrays
<?php
// function to recursively traverse nested arrays
function arrayTraverse($arr) {
// check if input is array
if (!is_array($arr)) { die ("Argument is not array!"); }
// iterate over array
foreach($arr as $value) {
// if a nested array
// recursively traverse
if (is_array($value)) {
arrayTraverse($value);
} else {
// process the element
print strtoupper($value) . " \n";
}
}
}
// define nested array
$data = array(
"United States",
array("Texas", "Philadelphia"),
array("California",
array ("Los Angeles", "San Francisco")));
// result: "UNITED STATES TEXAS PHILADELPHIA CALIFORNIA LOS ANGELES SAN
FRANCISCO"
arrayTraverse($data);
?>
Randomizing Arrays
<?php
// define array of numbers from 1 to 5
$numbers = range(1,5);
// shuffle array elements randomly
// result: "3, 5, 1, 2, 4" (example)
shuffle($numbers);
echo join (", ", $numbers);
?>
<?php
// define array of numbers from 1 to 12
$numbers = range(1,12);
// pick 5 random keys from the array
$randKeys = array_rand($numbers, 5);
// print the chosen elements
// result: "3, 5, 1, 2, 4" (example)
echo join (", ", $randKeys);
?>
Reversing Arrays
<?php
// define array of numbers
$numbers = array("one", "two", "three", "four", "five");
// return an array with elements reversed
// result: ("five", "four", "three", "two", "one")
print_r(array_reverse($numbers));
?>
Searching Arrays
<?php
// define associative array
$data = array(
"UK" => "United Kingdom",
"US" => "United States of America",
"IN" => "India",
"AU" => "Australia");
// search for key
// result: "Key exists"
echo array_key_exists("UK", $data) ? "Key exists" : ∝
"Key does not exist";
// search for value
// result: "Value exists"
echo in_array("Australia", $data) ? "Value exists" : ∝
"Value does not exist";
?>
Sorting Arrays
<?php
// define indexed array
$animals = array("wolf", "lion", "tiger", "iguana", "bear",∝
"zebra", "leopard");
// sort alphabetically by value
// result: ("bear", "iguana", "leopard", "lion", "tiger", "wolf",
"zebra")
sort($animals);
print_r($animals);
?>
Merging Arrays
<?php
// define arrays
$statesUS = array("Maine", "New York", "Florida", "California");
$statesIN = array("Maharashtra", "Tamil Nadu", "Kerala");
// merge into a single array
// result: ("Maine", "New York", ..., "Tamil Nadu", "Kerala")
$states = array_merge($statesUS, $statesIN);
print_r($states);
?>
<?php
// define arrays
$ab = array("a" => "apple", "b" => "baby");
$ac = array("a" => "anteater", "c" => "cauliflower");
$bcd = array("b" => "ball", "c" => array("car", "caterpillar"),∝
"d" => "demon");
// recursively merge into a single array
$abcd = array_merge_recursive($ab, $ac, $bcd);
print_r($abcd);
?>
Comparing Arrays
<?php
// define arrays
$salt = array("sodium", "chlorine");
$acid = array("hydrogen", "chlorine", "nitrogen");
// get all elements from $acid
// that also exist in $salt
// result: ("chlorine")
$intersection = array_intersect($acid, $salt);
print_r($intersection);
?>
Use PHP’s array_diff() function to find the elements that exist in either one
of the two arrays, but not both simultaneously:
<?php
// define arrays
$salt = array("sodium", "chlorine");
$acid = array("hydrogen", "chlorine", "nitrogen");
// get all elements that do not exist
// in both arrays simultaneously
// result: ("hydrogen", "nitrogen", "sodium")
$diff = array_unique(array_merge(∝
array_diff($acid, $salt), array_diff($salt, $acid)
));
print_r($diff);
?>
Reversing Strings
<?php
// define string
$cards = "Visa, MasterCard and American Express accepted";
// reverse string
// result: "detpecca sserpxE naciremA dna draCretsaM ,asiV"
$sdrac = strrev($cards);
echo $sdrac;
?>
Repeating Strings
<?php
// define string
$laugh = "ha ";
// repeat string
// result: "ha ha ha ha ha ha ha ha ha ha "
$rlaugh = str_repeat($laugh, 10);
echo $rlaugh;
?>
Truncating Strings
<?php
function truncateString($str, $maxChars=40, $holder="...") {
// check string length
// truncate if necessary
if (strlen($str) > $maxChars) {
return trim(substr($str, 0, $maxChars)) . $holder;
} else {
return $str;
}
}
// define long string
$str = "Just as there are different flavors of client-side scripting,∝
there are different languages that can be used on
the server as well.";
// truncate and print string
// result: "Just as there are different flavours of..."
echo truncateString($str);
// truncate and print string
// result: "Just as there are di >>>"
echo truncateString($str, 20, " >>>");
?>
Parsing URLs
<?php
// define URL
$url = "http://www.melonfire.com:80/community/columns/trog/ ∝
article.php?id=79 &page=2";
// parse URL into associative array
$data = parse_url($url);
// print URL components
foreach ($data as $k=>$v) {
echo "$k: $v \n";
}
?>
Searching Strings
<?php
// define string
$html = "I'm <b>tired</b> and so I <b>must</b> go
<a href='http://domain'>home</a> now";
// check for match
// result: "Match"
echo ereg("<b>(.*)+</b>", $html) ? "Match" : "No match";
?>
Use a regular expression with PHP’s preg_match() function:
<?php
// define string
$html = "I'm <b>tired</b> and so I <b>must</b> go
<a href='http://domain'>home</a> now";
// check for match
// result: "Match"
echo preg_match("/<b>(.*?)<\/b>/i", $html) ? "Match" : "No match";
?>