Docsity

PHP Arrays: Types, Building, Functions, and Operations, Lecture notes of Computer Science

Partial preview of the text

Download PHP Arrays: Types, Building, Functions, and Operations and more Lecture notes Computer Science in PDF only on Docsity!

ARRAY

S

Array

s

 Generally, array is a collection of homogeneous elements.  In Php, arrays are lists of bits of information mapped with keys and stored under one variable name.  For example, you can store a person’s name and address or a list of states in one variable. 2

Numeric

array

1.In the following example the index are automatically assigned (the index starts at 0): Eg: $cars1="Saab";cars=array(“ford",“audi","BMW","Toyota" ); 2.In the following example we assign the index manually: $cars1="Saab";cars[0]=“ford"; $cars1="Saab";cars[1]=“audi"; $cars1="Saab";cars[2]="BMW"; $cars1="Saab";cars[3]="Toyota";

In the following example you access the variable values by referring to the array name and index:

"; } ?>

Associative

array

 An associative array, each ID key is associated with a value.  When storing data about specific named values, a numerical array is not always the best way to do it.  With associative arrays we can use the values as keys and assign values to them.

 $cars1="Saab";ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34); <?php $ages[“Peter”] = "32"; $ages[“Quagmire”] = "30"; $ages[“Joe”] = "34"; echo "Peter is ". $ages[“Peter”]. " years old."; ?>

Loop

through an

associative

array

<?php $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); foreach($age as $x => $x_value) { echo "Key=". $x. ", Value=". $x_value; echo "
"; } ?>

Building up an

Array

 You can allolillye a new item in the array and add a value at the same time using empty square braces [] on the right hand side of an assignment statement $va = array(); $va[] = "Hello"; $va[] = "World"; print_r($va); Array( [0] => Hello [1] => World )

Building up an

Array

 You can also add new items in an array using a key as well $za = array(); $za["name"] = "Chuck"; $za["course"] = "PHPIntro"; print_r($za); Array( [name] => Chuck [course] => ) PHPIntro

Arrays

of

Arrays

$products = array( 'paper' => array( 'copier' => "Copier & Multipurpose ", 'inkjet' => "Inkjet Printer", 'laser' => "Laser Printer", 'photo' => "Photographic Paper"), 'pens' => array( 'ball' => "Ball Point", 'hilite' => "Highlighters", 'marker' => "Markers"), 'misc' => array( 'tape' => "Sticky Tape", 'glue' => "Adhesives", 'clips' => "Paperclips")

The elements of an array

can be many things other

than a string or integer.

You can even have

objects or other arrays.

); echo $products["pens"]["marker"]; Markers

$cars1="Saab";a[]=array(1,

$cars1="Saab";a[]

[]=array(0=>array(9,8),1=>

array)

Array

Function

s

array_sum(arra

y)

 The array_sum(array) function returns the sum of all the values in the array. <?php $a=array(1=>"5",2=>"15",3=>“25"); print_r (array_sum($a)); ?> 45