PHP Array Function
PHP Array Function
PHP Array Function
Output:
Array
(
[0] => Donald
[1] => Jim
)
array_push($arr, $val) This function adds an element to Code:
the end of an array. $data = array("Donald", "Jim", "Tom");
array_push($data, "Harry");
print_r($data);
?>
Output:
Array
(
[0] => Donald
[1] => Jim
[2] => Tom
[3] => Harry
)
array_shift($arr) This function removes an element Code:
from the beginning of an array. $data = array("Donald", "Jim", "Tom");
array_shift($data);
print_r($data);
?>
Output:
Array
(
[0] => Jim
[1] => Tom
)
array_unshift($arr, $val) This function adds an element to Code:
the beginning of an array. $data = array("Donald", "Jim", "Tom");
array_unshift($data, "Sarah");
print_r($data);
?>
Output:
Array
(
[0] => Sarah
[1] => Donald
[2] => Jim
[3] => Tom
)
each($arr) This function is most often used to Code:
iteratively traverse an array. Each $data = array("hero" => "Holmes",
time each() is called, it returns the "villain" => "Moriarty");
current key-value pair and moves while (list($key, $value) = each($data)) {
the array cursor forward one echo "$key: $value \n";
element. This makes it most }
suitable for use in a loop. ?>
Output:
hero: Holmes
villain: Moriarty
sort($arr) This function sorts the elements Code:
of an array in ascending order. $data = array("g", "t", "a", "s");
String values will be arranged in sort($data);
ascending alphabetical order. print_r($data);
Note: Other sorting functions ?>
include asort(), arsort(), ksort(),
krsort() and rsort(). Output:
Array
(
[0] => a
[1] => g
[2] => s
[3] => t
)
array_flip($arr) The function exchanges the keys Code:
and values of a PHP associative $data = array("a" => "apple", "b" =>
array. "ball");
Use this function if you have a print_r(array_flip($data));
tabular (rows and columns) ?>
structure in an array, and you
want to interchange the rows and Output:
columns. Array
(
sort() - sort arrays [apple] => a
in ascending order [ball] => b
rsort() - sort )
arrays in
descending order
asort() - sort
associative arrays in
ascending order,
according to the
value
ksort() - sort
associative arrays in
ascending order,
according to the key
arsort() - sort
associative arrays in
descending order,
according to the
value
krsort() - sort
associative arrays in
descending order,
according to the key
Output:
Array
(
[0] => 9
[1] => 18
[2] => 27
[3] => 36
)
$_SERVER['REQUEST_METHOD'] Returns the request method used to access the page (suc
$_SERVER['QUERY_STRING'] Returns the query string if the page is accessed via a que
$_SERVER['REMOTE_HOST'] Returns the Host name from where the user is viewing th
$_SERVER['REMOTE_PORT'] Returns the port being used on the user's machine to com
the web server
$_SERVER['SERVER_PORT'] Returns the port on the server machine being used by the
communication (such as 80)
$_SERVER['SERVER_SIGNATURE'] Returns the server version and virtual host name which a
server-generated pages
$_SERVER['PATH_TRANSLATED'] Returns the file system based path to the current script