0% found this document useful (0 votes)
91 views31 pages

PHP Arrays

Arrays allow storing multiple values in a single variable. An array can be created using the array() function or by assigning values to numeric indices. Arrays can store heterogeneous data types and be accessed sequentially or randomly by key. Common array functions include sort(), each(), foreach, explode(), implode() to manipulate array elements.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
91 views31 pages

PHP Arrays

Arrays allow storing multiple values in a single variable. An array can be created using the array() function or by assigning values to numeric indices. Arrays can store heterogeneous data types and be accessed sequentially or randomly by key. Common array functions include sort(), each(), foreach, explode(), implode() to manipulate array elements.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 31

Arrays

 You can create an array with the array function, or use the
explode function (this is very useful when reading files
into web programs…)
$my_array = array(1, 2, 3, 4, 5);
$pizza = "piece1 piece2 piece3
piece4 piece5 piece6";
$pieces = explode(" ", $pizza);

 An array is simply a variable representing a keyed list


 A list of values or variables
 If a variable, that var can also be an array
 Each variable in the list has a key
 The key can be a number or a text label
Arrays
• Arrays are lists, or lists of lists, or list of lists of lists, you
get the idea--Arrays can be multi-dimensional
• Each array element consists of two parts: a key and a
value.
• Array elements can be addressed by either by number or
by name (strings)
• If you want to see the structure of an array, use the print_r
function to recursively print an array inside of pre tags
There are two ways to create an array in PHP.
For example,
if no array named $list currently exists, the
following statement creates one:
$list[0] = 17;

$list[1] = "Today is my birthday!";


$list[] = 42;
The second way to create an array is with the array construct

PHP interpreter will furnish the numeric keys. For example,


the assignment
$list = array(17, 24, 45, 91);

Keys can be implicitly specified as


$list = array(1 => 17, 2 => 24, 3 => 42, 4 => 91);

An array construct with empty parentheses creates an empty


array
$list = array();
The following statement creates an array that has the form of a
hash:
$ages = array("Joe" => 42, "Mary" => 41, "Bif" => 17);

Mixtures of both( array & hash).


For example,
$stuff = array("make" => "Cessna", "model" => "C210“, "year" =>
1960, 3 => "sold");
The list construct can be used to assign multiple elements of an
array to scalar variables in one statement.

For example, in the statements

$trees = array("oak", "pine", "binary");


list($hardwood, $softwood, $data_structure) = $trees;

$hardwood, set to "oak“,


$softwood, set to "pine",
$data_structure are set to "binary"
A whole array can be deleted with unset, as
with a scalar variable.
Individual elements of an array also can be
removed with unset, as

$list = array(2, 4, 6, 8);


unset($list[2]);

After executing these statements,


$list has three remaining elements with keys
0, 1, and 3 and elements 2, 4, and 8.
$highs = array("Mon" => 74, "Tue" => 70, "Wed"
=> 67,
"Thu" => 62, "Fri" => 65);
$days = array_keys($highs);
$temps = array_values($highs);
The existence of an element of a specific key can
be determined with the array_key_exists
function, which returns a Boolean value.

$highs = array("Mon" => 74, "Tue" => 70, "Wed" => 67,"Thu" =>
62, "Fri" => 65);

if (array_key_exists("Tue", $highs))
{$tues_high = $highs["Tue"];
print "The high on Tuesday was $tues_high <br />“;}

else print "There is data for Tuesday in the \$highs array <br />";
$list = array("Bob", "Fred", "Alan", "Bozo");
$len = sizeof($list);

Convert between strings and arrays can be done


with the implode and explode functions

The explode function explodes a string into


substrings and returns them in an array

$str = "April in Paris, Texas is nice";


$words = explode(" ", $str);
Now $words contains ("April", "in", "Paris," ,
"Texas", "is", "nice").
The implode function does the inverse of explode.
Given a separator character (or a string) and an array, it
concatenates the elements of the array together,
placing the given separator string between the
elements, and returns the result as a string.

Consider, for example,


$words = array(“Are", "you", “alright");
$str = implode(" ", $words);

Now $str has "Are you alright"


Access array
PHP includes several different ways to access array
elements in sequential order.
Every array has an internal pointer that references one
element of the array called as the current pointer.

$cities = array("Hoboken", "Chicago", "Moab");


$city = current($cities);
print("The first city is $city <br />");

output :
The first city is Hoboken
list of all the elements of that array:

$city = current($cities);
print("$city <br />");
while ($city = next($cities))
print("$city <br />");

The loop iterations stop when the value of the current element is
FALSE

• the prev function returns the value of the element referenced


by the current pointer
• the reset function sets the current pointer to the first element
• array_push, array_pop
• One problem with using the next function for loop control
occurs when the array includes an element with the value
FALSE.
• The loop iterations stop when the value of the current
element is FALSE, rather than when the end of the array is
reached.
• The each function, which returns a two-element array
consisting of the key and the value of the current element,
avoids this problem.

• Another difference between each and next is that each


returns the element being referenced by the current pointer
and then moves that pointer.

• The next function first moves the current pointer and then
returns the value being referenced by the current pointer.
The each function, which returns a two-element
array consisting of the key and the value of the
current element, avoids this problem

$salaries = array("Mike" => 42500, "Jerry" => 51250,


"Fred" => 37920);
while ($employee = each($salaries)) {
$name = $employee["key"];
$salary = $employee["value"];
print("The salary of $name is $salary <br />");
}
foreach
The foreach statement is designed to build loops that process all
the elements of an array.

This statement has two forms:


1) foreach (array as scalar_variable) loop body

foreach ($list as $temp)


print("$temp <br />");
2) foreach (array as key => value) loop body

$lows = array("Mon" => 23, "Tue" => 18, "Wed"


=> 27);
foreach ($lows as $day => $temp)
print("The low temperature on $day was $temp
<br />");
Sorting array
• The sort function, which takes an array as a parameter, sorts
the values in the array, replacing the keys with the numeric
keys, 0, 1, 2, . . . .

• The asort function is used to sort arrays that correspond to


hashes. It sorts the elements of a given array by their values,
but keeps the original key-value associations.

• The ksort function sorts its given array by keys, rather than
values. The key-value associations are maintained by the
process.
function
• function names are not case sensitive
• default parameter-passing mechanism of PHP is pass by
value

function max_abs($first, $second) {


$first = abs($first);
$second = abs($second);
if ($first >= $second)
return $first;
else
return $second;
}
• Pass-by-reference parameters can be specified in PHP in
two ways.
1) One way is to add an ampersand (&) to the beginning
of the name of the formal parameter
2) The other way to specify pass by reference is to add an
ampersand to the actual parameter

function set_max(&$;max, $first, $second) {


If ($first >= $second)
$max = $first;
else
$max = $second;
}
Local scope
function summer($list) {
$sum = 0;
foreach ($list as $value)
$sum += $value;
return $sum;
}
$sum = 10; $nums = array(2, 4, 6, 8); $ans = summer($nums);
print "The sum of the values in \$nums is: $ans <br />";
print "The value of \$sum is still: $sum <br />";

Upon interpretation, this produces the following output:


The sum of the values in $nums is: 20
The value of $sum is still: 10
Global scope
$big_sum = 0;

function summer ($list) {


global $big_sum; //** Get access to $big_sum
$sum = 0;
foreach ($list as $value)
$sum += $value; $big_sum += $sum;
return $sum;}
...
$ans1 = summer($list1); $ans2 = summer($list2);
...
print "The sum of all array elements is: $big_sum <br />";
Static/ Lifetime of variables
function do_it ($param) {
static $count = 0;
count++;
print "do_it has now been called $count times <br />“;}

The default lifetime of local variables in a PHP function is


from the time the variable is first used (i.e., when
storage for it is allocated) until the function’s
execution terminates.
To support history sensitivity, a function must have static
local variables.
Pattern Matching
if (preg_match("/^PHP/", $str))
print "\$str begins with PHP <br />";
else
print "\$str does not begin with PHP <br />";
------------------------------------
$fruit_string = "apple : orange : banana";
$fruits = preg_split("/ : /", $fruit_string);
The array $fruits now has ("apple", "orange", "banana").
Validation – ex1

$name = trim($_POST['name']);
if(empty($name)) {
echo "Please enter your name"; exit;
}

echo "Success";
Validationn- ex2
if(empty($_POST['selectedcake']))
{ $select_cake_error = "Please select a cake
size";
$error=true;
} else
{ $selected_cake = $_POST['selectedcake']; }
file_exists
<?php $file = "data.txt";
// Check the existence of file
if(file_exists($file)){
// Attempt to open the file
$handle = fopen($file, "r"); }
else
{ echo "ERROR: File does not exist."; }
?>
Files in PHP
• fread
• file
• file_get_contents
• fgets
• fgetc
• ----------------
• fwrite
• file_put_contents
file
<?php $file = "data.txt"; // Check the
existence of file

if(file_exists($file))
{ // Reads and outputs the entire file
file($file) or die("ERROR: Cannot open
the file."); }
else
{ echo "ERROR: File does not exist."; }
?>
file_get_contents
<?php $file = "data.txt";
// Check the existence of file
if(file_exists($file)){
// Reading the entire file into a string
$content = file_get_contents($file) or
die("ERROR: Cannot open the file.");
// Display the file content
echo $content; }
else{ echo "ERROR: File does not exist.";
} ?>
file_put_contents
<?php $file = "note.txt";
// String of data to be written $data =
"The quick brown fox jumps over the
lazy dog.";
// Write data to the file
file_put_contents($file, $data) or
die("ERROR: Cannot write the file.");
echo "Data written to the file
successfully."; ?>

You might also like