0 0
Read Time:10 Minute, 59 Second

FREE php course Lecture #4 PHP Arrays An array in PHP is actually an ordered list that stores multiple values. All items in the list have at
least one thing in common that set the sequence of values of the item. For example, there are four
seasons in a year. Winter must come before spring, spring must come before summer, and more.
“Season” is the name of array, which contains four items, spring, summer, fall, and winter, in
sequence.

In PHP, it’s easy to create and initialize PHP arrays. There are two methods to choose from, and
we’ll be discussing both of them in this lecture. You can
create an array with the array identifier.
create an array with the array() function.

 

Create an array with the array identifier ..– FREE php course

The simplest way to create a PHP array is to use the array identifier, which is a set of empty square
brackets. For example:

$season[0]=”Spring”;
$season[1]=”Summer”;
$season[2]=”Fall”;
$season[3]=”Winter”;

The syntax is:

ArrayName[index]=value

By default, the index numbers start at zero, and arrays are assumed to be zero-based. This means
that the index number of the last element is typically one less than the number of elements. In other
words, if an array has four elements, the last value will be referenced as $season[3].

You can create an array, in PHP, by simply assigning values. For example:

$season[]=”Spring”;
$season[]=”Summer”;
$season[]=”Fall”;
$season[]=”Winter”;

PHP will automatically assign the index value for each element in the array. Try the following two
examples; they will yield the same results.

free php course
free php course

The output for both examples will look like:

Apple :1st item.
Tangerine : 4th item.

Create an array with the array() function …,,, FREE php course

In PHP, you can specify an array with array(). This is the method of choice when you have multiple
values to assign at one time. For example:

$season = array(“Spring”,”Summer”,”Fall”,”Winter”);

Each element is surrounded by quotes and separated by commas. The number of elements is
variable, so you can specify as many elements as you need to initialize the array.

For example:

<?php
$season = array(“Spring”,”Summer”,”Fall”,”Winter”);
echo $season[2] . ‘($season[2]) gets the 3rd item.’;
echo $season[3] . ‘($season[3]) gets the 4th item.’;
?>

will yield the following output:

Fall($season[2]) gets the 3rd item.Winter($season[3]) gets the 4th item.

Be sure to review the previous section to understand why the $season[2] value enclosed by single
quotes (‘) are escaped.

Defining the starting index value

By default, PHP arrays are zero-based. This means that the index value for the last element is
always one less than the total number of elements. If you have an array of all 50 US states, the first
element would be $states[0], and the last one will be accessed as $states[49]. If you’d like to change
the default behavior, use the “=>” operator.

For example:

$state = array(1 => “Alabama”, “Alaska”, “California”);

Consequently the first element, “Alabama”, would be accessed as $state[1] instead of the default
$state[0]. Compare the following codes and their results.

<?php
$state = array(1 => “Alabama”, “Alaska”, “California”);
echo $state[0];
?>

The output is Some kind of error message like “Undefined offset: 0”. Now try,

<?php
$state = array(1 => “Alabama”, “Alaska”, “California”);
echo $state[1];
?>

The output is:

Alabama

In PHP, there are three kind of arrays:
• Numeric array – An array with a numeric index.
• Associative array – An array where each ID key is associated with a value.
• Multidimensional array – An array containing one or more arrays.

All the above examples are numeric array. It is time to move on to associative array.

 

Creating Associative Arrays in PHP

When you create a simple PHP array, the starting index value is zero by default. However, you can
use string values as the index for each element in the array. When a PHP array uses strings for the
index values, it is known as an associative array.

Option 1: Create associative arrays with the array() function

To create an associative array in PHP, the easiest way is to use the array() function. However,
unlike a simple PHP array, an associative array in PHP needs both the index value, known as the
key, and the value of the element, known as the value. These are often referred to as key-value
pairs. Here’s an example:

$StateCapital = array(“AL”=> “Montgomery”, “LA”=> “Baton Rouge”,
“TX”=> “Austin”);

The example uses the two letter abbreviation for Alabama, Louisiana, and Texas as the key, or
index value. The capitals for those states, Montgomery, Baton Rouge, and Austin, are the values.
Notice that keys and values are separated by ‘=>’, and each key-value pair is separated by commas.

 

Option 2: Create associative arrays with the array identifier

Another way to create associative arrays in PHP is to use the array identifier.

$StateCapital[“AL”] = “Montgomery”;
$StateCapital[“LA”] = “Baton Rouge”;
$StateCapital[“TX”] = “Austin”;

For example:

<?php
$gender[“F”]=”Female”;
$gender[“M”]=”Male”;
$gender[“U”]=”Unidentifiable”;
echo “Jennifer Lopez is ” . $gender[“F”] .”!”;
?>

will yield the following output:

Jennifer Lopez is Female!
The following will yield “Bill Clinton is Male!”:

<?php
$gender = array(“F”=>”Female”, “M”=>”Male”, “U”=>”Unidentified”);
echo “Bill Clinton is ” . $gender[“M”] .”!”;
?>

Note that you can use both methods on the same array to add new elements.

$StateCapital = array(“AL”=> “Montgomery”, “LA”=> “Baton Rouge”,
“TX”=> “Austin”);
$StateCapital[“CA”] = “Sacramento”;

Consider the following example, the $StateCapital[“CA”] element is added after the array is created,
and the output is Sacramento.

<?php
$StateCapital = array(“AL”=> “Montgomery”, “LA”=> “Baton Rouge”,
“TX”=> “Austin”);
$StateCapital[“CA”] = “Sacramento”;
echo “The state capital of California is ” . $StateCapital[“CA”];
?>

One thing to keep in mind is that your keys, or index values, should be short and meaningful. Not
only will it be easier to maintain and modify your PHP script, but the script will also run more efficiently.

Another good thing to remember is not to access an associative array value within a string. Since the
keys and values are enclosed in double quotations, they can’t be embedded within a string. Instead,
use the concatenation operator to combine the string values.

Array is very useful to the design of dynamic web site. The following PHP code will randomly
display different graphics with hyperlink. Portal web sites, such as MSN.com and Yahoo.com, use
these techniques to randomly display advertisement on their sites.

<?php
$r = rand(0,9); //using rand() to generate random number
$graphic = array( //array of graphic file name
“01.gif”,
“02.gif”,
“03.gif”,
“04.gif”,
“05.gif”,
“06.gif”,
“07.gif”,
“08.gif”,
“09.gif”,
“10.gif”,
);
//use concatenation operator to combine file name to web site URL
$image =”http://www.mysite.com/images/” . $graphic[$r];
$url = array( // array of sites to link with each graphic
“http://www.cnn.com”,
“http://www.nbc.com”,
“http://www.abc.com”,
“http://www.fox.com”,
“http://www.mtv.com”,
“http://www.hbo.com”,
“http://www.pbs.com”,
“http://www.tnt.com”,
“http://www.tmc.com”,
“http://www.upn.com”,
“http://www.cbs.com”
);
echo “<a href=$url[$r]>”;
echo “<img src=$image border=0></a>”;
?>

Note: When you visit this site, click “Refresh” on the web browser toolbar to see how the code
displays different graphics dynamically.

Multi-Dimensional Arrays

PHP arrays can contain arrays. In other words, a multidimensional array is an array except that
holds other arrays as a value (in the regular key=>value pair of an array), which in turn hold other
arrays as well. For example, the following code creates three arrays: $SF, $Action, and $Romance.

$SF = array(“2001”, “Alien”,”Terminator”);
$Action = array(“Swing Girls”,”Premonition”,”Infection”);
$Romance = array(“Sleepless in Seattle”,”You’ve Got Mail”,”All of Me”);

A multidimensional array however, will contain another array as a possible value; for example, the $genre super-array contains all the three arrays.

<?php
$genre = array (
“SF” => array(“Star Wars”, “Alien”,”Terminator”),
“Action” => array(“Swing Girls”,”Premonition”,”Infection”),
“Romance” => array(“Sleepless in Seattle”,”You’ve Got
Mail”,”All of Me”)
);
print_r($genre);
?>

The “SF”, “Action”, and “Romance” are three individual arrays, but they are now elements to the
“genre” array. So the output of the above code looks:

Array
(
[SF] => Array
(
[0] => Star Wars
[1] => Alien
[2] => Terminator
)
[Action] => Array
(
[0] => Swing Girls
[1] => Premonition
[2] => Infection
)
[Romance] => Array
(
[0] => Sleepless in Seattle
[1] => You’ve Got Mail
[2] => All of Me
)
)

The above sample output shows the hierarchy of the genre array and its element arrays. You can
interpret the hierarchy using the format of: $genre[“SF”][0] = “Star War”. Formally, the
syntax is:

parentArrayName[“childArrayName”][“childElementKey”];

The following example further explains how to display values of each of the elements.

<?php
$genre = array (
“SF” => array(“Star Wars”, “Alien”,”Terminator”),
“Action” => array(“Swing Girls”,”Premonition”,”Infection”),
“Romance” => array(“Sleepless in Seattle”,”You’ve Got
Mail”,”All of Me”)
);
echo $genre[“SF”][0] . “<br />”;
echo $genre[“SF”][1] . “<br />”;
echo $genre[“SF”][2] . “<br />”;
echo $genre[“Action”][0] . “<br />”;

cho $genre[“Action”][1] . “<br />”;
echo $genre[“Action”][2] . “<br />”;
echo $genre[“Romance”][0] . “<br />”;
echo $genre[“Romance”][1] . “<br />”;
echo $genre[“Romance”][2] . “<br />”;
?>

The same format applies to number-based array. For example:

<?php
$lists = array ( 1 => array( 12, 14, 16), 2 => array(11, 13, 15) );
print_r($lists);
?>
The output looks,
Array
(
[1] => Array
(
[0] => 12
[1] => 14
[2] => 16
)
[2] => Array
(
[0] => 11
[1] => 13
[2] => 15
)
)
To display each value, use:

<?php
$lists = array ( 1 => array( 12, 14, 16), 2 => array(11, 13, 15) );
echo $lists[“1”][0] . “<br>\n”;
echo $lists[“1”][1] . “<br>\n”;
echo $lists[“1”][2] . “<br>\n”;
echo $lists[“2”][0] . “<br>\n”;
echo $lists[“2”][1] . “<br>\n”;
echo $lists[“2”][2] . “<br>\n”;
?>

Review Questions .., FREE php course

1. Given the following code, what is the output?

<?php
$n = array(1, 2, 3, 4);
echo $n[3];
?>

A. 1
B. 2
C. 3
D. 4

2. Given the following code, what is the output?

<?php
$n = array(1, 2, 3, 4);
echo $n[0]+$n[3];
?>

A. 5
B. 6
C. 7
D. 8

3. Given the following code, what is the output?

<?php
$a[] = 1;
$a[] = 2;
$a[] = 3;
$a[] = 4;
echo $a[2];
?>

A. 1
B. 2
C. 3
D. 4

4. Given the following code, what is the output?

<?php
$a[2] = 1;
$a[3] = 2;
$a[6] = 3;
$a[9] = 4;
echo $a[2];
?>

A. 1
B. 2
C. 3
D. 4

5. Given the following code:

<?php
$course[“cis245”] = “Perl Programming”;
$course[“cis246”] = “PHP Programming”;
$course[“cis247”] = “Python Programming”;
$course[“cis248”] = “Plank Programming”;
?>

which generate the following output?

PHP Programming

A. <?php print $course[“cis245”]
B. <?php print $course[“cis246”]
C. <?php print $course[“cis247”]
D. <?php print $course[“cis248”]

6. Given the following code,

<?php
$fruit = array(“A” => “Apple”,
“B” => “Banana”,
“G” => “Grape”,
“O” => “Orange”); ?>

which generate the following output?

I like banana!

A. print “I like ” + $fruit[“B”] . “!”;
B. print “I like ” . $fruit[“B”] . “!”;
C. print “I like ” $fruit[“B”] “!”;
D. print “I like ” + $fruit[“B”] + “!”;

7. Given the following code, which is the correct output?

<?php
$state = array(1 => “Alabama”, “Alaska”, “California”, “Nevada”);
echo $state[3];
?>

A. Alabama
B. Alaska
C. California
D. Nevada

8. Given the following code, which combination can yield a result of 10?

<?php $x = array( 9, 6, 4, 2, 5, 8, 9); ?>

A. $x[3] + $x[5];
B. $x[0] + $x[4] – $x[2];
C. $x[2] * $x[4];
D. $x[1] + $x[6];

9. Given the following code, which displays the value 99?

<?php $x = array ( 1 => array( 101, 102), 2 => array(100, 99) ); ?>

A. echo $x[“1”][0];
B. echo $x[“1”][1];
C. echo $x[“2”][0];
D. echo $x[“2”][1];

10. Given the following code, which displays the value Infection?

<?php
$genre = array (
“SF” => array(“Star Wars”, “Alien”,”Terminator”),
“Action” => array(“Swing Girls”,”Premonition”,”Infection”),
“Romance” => array(“Sleepless in Seattle”,”You’ve Got
Mail”,”All of Me”)
); ?>

A. echo $genre[“Action”][0] . “<br />”;
B. echo $genre[“Action”][1] . “<br />”;

C. echo $genre[“Action”][2] . “<br />”;
D. echo $genre[“Action”][3] . “<br />”;

FULL LIST OF LECTURSE HERE

FREE php course

Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %
Previous post free PHP programming course E3 learn to code
Next post free PHP programming course E5 learn to code

Average Rating

5 Star
0%
4 Star
0%
3 Star
0%
2 Star
0%
1 Star
0%

Leave a Reply

Your email address will not be published. Required fields are marked *

Close