SlideShare a Scribd company logo
UNIT – 4
ARRAYS



                                Dr. P S V S Sridhar
                             Assistant Professor (SS)
                         Centre for Information Technology




           | Jan 2013|                                       © 2012 UPES
Introduction to Array


-An array can store one or more values in a single variable name.


-Each element in the array is assigned its own ID so that it can be
  easily accessed.
-$array[key] = value;


 $arrayname[]=value


 array() language construct




            Jul 2012
             Jan 2013                                          © 2012 UPES
Array in PHP
 1)   Numeric Array
 2)   Associative Array
 3)   Multidimensional Array




        Jul 2012
         Jan 2013              © 2012 UPES
Numeric Array
- A numeric array stores each element with a numeric ID key.
- 2 ways to write a numeric array.
1. Automatically
Example:                 $names = array("Peter","Quagmire","Joe");


2. Manually
Example1:                  $names[0] = "Peter"; $names[1] = "Quagmire";
                         $names[2] = "Joe";
Example 2:              $name[] =”Peter”; $name[] =“Quagmire”; $name[] = “joe”;
In the above case we are adding sequential elements that should have
numerical counting upward from zero.



            Jul 2012
             Jan 2013                                                     © 2012 UPES
Associative Arrays
 -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.
 Example:            Using an array to assign an age to a person.
  $ages = array(”Brent"=>42, ”Andrew"=>25, "Joshua”=>16);
  $ages[‟Brent'] = 42;
  $ages[‟Andrew'] = 25;
  $ages['Joshua'] = 16;
 Eamample:
   $f = array(0=>”apple”, 1=>”orange”, 2=>”banana”, 3=>”pear”);
 In the above example index values are 0,1,2,3
         Jul 2012
          Jan 2013                                                  © 2012 UPES
Array creation:
 following creates an array with numeric index
 $icecream_menu=array(275,160,290,250);

which is equivalent to the following array creation

$icecream_menu=array(0=>275,1=>160,2=>290,3=>250);

 Arrays can be created with other scalar values as well as mix of them
 $icecream_menu1[-1]=275;
  $icecream_menu1[„item 2‟]=160;
  $icecream_menu1[3.4]=290;
  $icecream_menu1[false]=250;
 An array with a mix of all values can also be created

  $icecream_menu=array(-1=>275,'item 2'=>160,3.4=>290,false=>250);

           Jul 2012
            Jan 2013                                             © 2012 UPES
Creating an Empty Array
  $marks=array();




         Jul 2012
          Jan 2013        © 2012 UPES
Finding the Size of an Array
 The count() function is used to find the number of elements in the array


 $icecream_menu=array('Almond Punch'=>275,'Nutty Crunch'=>160,'Choco
  Dip'=>290,'Oreo Cherry'=>250);
  print "There are ".count($icecream_menu) ." flavours of icecreams available!!"


 prints the following
 There are 4 flavours of icecreams available!!




             Jul 2012
              Jan 2013                                                  © 2012 UPES
Printing an Array in a readable way
 The print_r() ,when passed an array, prints its contents in a readable
  way.
 $icecream_menu=array('Almond Punch'=>275,'Nutty Crunch'=>160,'Choco
  Dip'=>290,'Oreo Cherry'=>250);
 print_r($icecream_menu);


 Output of the above code will be
  Array ( [Almond Punch] => 275 [Nutty Crunch] => 160 [Choco Dip] => 290
  [Oreo Cherry] => 250 )




            Jul 2012
             Jan 2013                                               © 2012 UPES
Iterating Array Elements
 The easiest way to iterate through each element of an array is with
  foreach(). The foreach()construct executes the block of code once for
  each element in an array.
 Syntax
 foreach($array as [$key =>] [&] $value)

  {   //block of code to be executed for each iteration                }
 $array – represents the array to be iterated
 $key is optional, and when specified, it contains the currently iterated
  array value‟s key, which can be any scalar value, depending on the key‟s
  type.
 $value holds the array value, for the given $key value.
 Using the & for the $value, indicates that any change made in the $value
  variable while iteration will be reflected in the original array($array) also.

            Jul 2012
             Jan 2013                                                      © 2012 UPES
Modifying Array while iteration
  Arrays can be modified during iteration in 2 ways.
  Direct Array Modification
  Indirect Array Modification




          Jul 2012
           Jan 2013                                     © 2012 UPES
Direct Array Modification
 Say for example we need to increase the price of the all icecreams by 50 .The following code helps us to update the
  price and display the revised price along with the old ones
 <html>
  <body>
  <h3 align="center"><i>Chillers...</i></h3>
  <table align="center">
  <tr bgcolor="#D7D7D7" ><td >Icecream Flavours</td><td>Price</td></tr>
  <?php
  $icecream_menu=array('Almond Punch'=>275,'Nutty Crunch'=>160,'Choco Dip'=>290,'Oreo Cherry'=>250);

   foreach($icecream_menu as $key=>$value)

   {

   print "<tr bgcolor='#F3F3F3'>";

   print "<td>".$key."</td><td>".$value."</td>";

   print "</tr>";

   }

   ?>
   </table>
   <h3 align="center"><i>Chillers Revised Price.....</i></h3>
   <table align="center">
   <tr bgcolor="#D7D7D7" ><td >Icecream Flavours</td><td>Price</td></tr>

                    Jul 2012
                     Jan 2013                                                                               © 2012 UPES
Contd…
  <?php
   foreach($icecream_menu as $key=>&$value)
   {
   //increase the price of all icecreams by 50

   $icecream_menu[$key]=$value+50;

   $value=$icecream_menu[$key];

   print "<tr bgcolor='#F3F3F3'>";

   print "<td>".$key."</td><td>".$value."</td>";

   print "</tr>";

   }
   ?>
   </table>
   </body>
   </html>
              Jul 2012
               Jan 2013                            © 2012 UPES
Indirect Array Modification
 foreach($array as [$key =>] [&] $value) {

  //block of code to be executed for each iteration

  }
 where “&‟ can be used with $value.Any change in $value,indirectly modifies
  the value of the array for the current key during the iteration.
 foreach($icecream_menu as $key=>&$value)

  {

  //increase the price of all icecreams by 50

  $value=$value+50;

  print "<tr bgcolor='#F3F3F3'>";

  print "<td>".$key."</td><td>".$value."</td>";

  print "</tr>";

  }
                   Jul 2012
                    Jan 2013                                         © 2012 UPES
Iterating Array with Numeric index
 Arrays with numeric index can be accessed using
 foreach()               and     for()
Ex1:
 $hobbies=array("Reading Books","Playing Golf","Watching
  Tennis","Dancing");
  foreach($hobbies as $hobby)
  {
  print "<br> $hobby ";
  }


Ex 2:
 for($i=0,$arraysize=count($hobbies);$i<$arraysize;$i++)

  print "<br> $hobbies[$i]";
              Jul 2012
               Jan 2013                                     © 2012 UPES
Multi dimensional Arrays
- In a multidimensional array, each element in the main array can
  also be an array.
- And each element in the sub-array can be an array, and so on.
Ex1:
$families = array
("Griffin"=>array ( "Peter","Lois", "Megan" ),
     "Quagmire"=>array ( "Glenn" ),
     "Brown"=>array ("Cleveland", "Loretta", "Junior" )
);
Ex2:
$icecream_menu=array('Almond
  Punch'=>array("single"=>275,"couple"=>425,"family"=>500),
  'Nutty Crunch'=>array("couple"=>375,"family"=>450),
  'Choco Dip'=>array("single"=>275,"Treat"=>425,"family"=>600),
  'Oreo Cherry'=>array("single"=>450,"family"=>525));
               Jul 2012
                Jan 2013                                          © 2012 UPES
Handling Multidimensional arrays
 $scores[“sam”][1] = 79;
 $scores[“sam”][2] = 74;
 $scores[“ellen”][1] = 69;
 $scores[“ellen”][2] = 84;
 Print_r($scores);


 Output:
 [sam] => array([1] =>79
                       [2] =>74
                       )
 [ellen] => array([1] => 69
                           [2] => 84
                       )
           Jul 2012
            Jan 2013                   © 2012 UPES
Handling Multidimensional arrays
 Ex:
 $scores[“sam”][] = 79;
 $scores[“sam”][] = 74;
 $scores[“ellen”][] = 69;
 $scores[“ellen”][] = 84;
 Here index start from 0.
 Ex:
 $scores = array(“sam” => array(79,74), “ellen” => array(69,84));




           Jul 2012
            Jan 2013                                                © 2012 UPES
Multi dimensional arrays in loops
 $scores[0][] = 79;
 $scores[0][] = 74;
 $scores[1][] = 69;
 $scores[1][] = 84;
 for($outer = 0; $outer < count($scores); $outer++)
   for($inner = 0; $inner < count($scores[$outer]); $inner++)
   {
         echo $scores[$outer][$inner];
    }




          Jul 2012
           Jan 2013                                             © 2012 UPES
Splitting and Merging Arrays
array_slice function will split array
Ex1:
          $ice_cream[“good”] = “orange”;
          $ice_cream[“better”] = “vanilla”;
          $ice_cream[“best”] = “rum raisin”;
          $ice_cream[“bestest”] = “lime”;
          $subarray = array_slice($ice_cream, 1,2);
 The index value of better and best will be stored in $subarray as vanilla rum raisin
Ex2:
<?php
$input = array("a", "b", "c", "d", "e");

$output = array_slice($input, 2); // returns "c", "d", and "e"
$output = array_slice($input, -2, 1); // returns "d"
$output = array_slice($input, 0, 3); // returns "a", "b", and "c“
?>
                 Jul 2012
                  Jan 2013                                                      © 2012 UPES
Splitting and Merging Arrays
array_merge will merge the arrays
Ex1:
$pudding = array(“vanilla”, “run raisin”, “orange”);
$ice_cream = array(“chocolate”,”pecan”,”strawberry”);
$desserts = array_merge($pudding, $ice_cream);


The elements of $pudding and $ice_cream will be stored in $desserts array.
Ex2:
<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>
Output:
Array ( [color] => green [0] => 2 [1] => 4 [2] => a [3] => b [shape] => trapezoid [4] => 4 )   © 2012 UPES
                 Jul 2012
                  Jan 2013
Sorting of Arrays
 Sort - Sorts the array values (loses key)
<?php

$fruits = array("lemon", "orange", "banana", "apple");
sort($fruits);
foreach ($fruits as $key => $val) {
echo "fruits[" . $key . "] = " . $val . "n";
}

?>
Output:
fruits[0] = apple fruits[1] = banana fruits[2] = lemon fruits[3] = orange




            Jul 2012
             Jan 2013                                                       © 2012 UPES
Sorting of Arrays
 Ksort - Sorts the array by key along with value
<?php
$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
ksort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $valn";
}
?>
Output:
a = orange b = banana c = apple d = lemon




            Jul 2012
             Jan 2013                                                  © 2012 UPES
Sorting of Arrays
  asort - Sorts array by value, keeping key association
 <?php
 $fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" =>
 "apple");
 asort($fruits);
 foreach ($fruits as $key => $val) {
 echo "$key = $valn";
 }
 ?>
 Output:
 c = apple b = banana d = lemon a = orange




           Jul 2012
            Jan 2013                                                   © 2012 UPES
Array functions
      count($ar) - How many elements in an array
      array_sum($ar) – sum of array values.
      sizeof($ar) – Identical to count()
      is_array($ar) - Returns TRUE if a variable is an array
      sort($ar) - Sorts the array values (loses key)
      ksort($ar) - Sorts the array by key along with value
      asort($ar) - Sorts array by value, keeping key association
      shuffle($ar) - Shuffles the array into random order
      $a = array() – Creates an array $a with no elements
      $a = range(1,5) – Create an array between 1 and 5. i.e., $a =
       array(1,2,3,4,5)
      in_array() – Takes two arguments: an element and an array. Returns
       true if the element contained as a value in the array.
      rsort(), arsort(), krsort() - Works similar to sort(), asort() and ksort()
       except that they sort the array in descending order
         Jul 2012
          Jan 2013                                                              © 2012 UPES
Array functions
 list():
 Assign array values to variable.
 Ex: $f = array(„apple‟,‟orange‟,‟banana‟);
       list($r,$o) = $f;
        The string apple is assigned to $r and orange is assigned to $o and no assignment of
    string banana.
 reset():
 Gives us a way to “rewind” that pointer to the beginning – it sets the pointer to the first
  key/value pair and then returned to stored value.
 next():
 which moves the current pointer ahead by one,
 prev():
 Which moves the pointer back by one.
 current():
 Returns the current element in an array
 end()
 Which moves2012 end of the array
           Jul to
            Jan 2013                                                                        © 2012 UPES
Next, current, Prev
  <?php

  $array = array('step one', 'step two', 'step three', 'step four');

  // by default, the pointer is on the first element
  echo current($array) . "<br />n"; // "step one"

  // skip two steps
  next($array);
  next($array);
  echo current($array) . "<br />n"; // "step three"

  // reset pointer, start again on step one
  reset($array);
  echo current($array) . "<br />n"; // "step one"

  ?>
           Jul 2012
            Jan 2013                                                   © 2012 UPES
Array functions
  Deleting from arrays: Just call unset()
  $a[0] = “wanted”;
  $a[1]=“unwanted”;
  $a[2]=“wanted again”;
  unset($a[1]);
  Deletes 1 key value. Now the above array contains two key values (0,2)




          Jul 2012
           Jan 2013                                                © 2012 UPES
Extracting Data from Arrays
  Extract function to extract data from arrays and store it in variable.
         $ice_cream[“good”] = “orange”;
         $ice_cream[“better”] = “vanilla”;
         $ice_cream[“best”] = “rum raisin”;
         extract($ice_cream);
         echo “$good = $good <br>”;
         echo “$better = $better <br>”;
         echo “$best = $best <br>”;
 Output:
 $good = orange
 $better = vanilla
 $best = rum raisin
           Jul 2012
            Jan 2013                                                        © 2012 UPES
Arrays and Strings
explode(): The function explode converts string into array format .
We can use explode() to split a string into an array of strings
$inp = "This is a sentence with seven words";
$temp = explode(‘ ', $inp);
print_r($temp);


Output:
Array( [0] => This [1] => is        [2] => a   [3] => sentence    [4] => with
[5] => seven [6] => words)
implode(): To combine array of elements in to a string
 $p = array("Hello", "World,", "I", "am", "Here!");
 $g = implode(" ", $p);
 Output: Hello World I am Here
           Jul 2012
            Jan 2013                                                    © 2012 UPES
Arrays and strings
 str_replace():
$rawstring = "Welcome Birmingham parent! <br />
Your offspring is a pleasure to have! We believe pronoun is learning a lot.<br />The faculty
simple adores pronoun2 and you can often hear them say "Attah sex!"<br />";
$placeholders = array('offspring', 'pronoun', 'pronoun2', 'sex');
$malevals = array('son', 'he', 'him', 'boy');
$femalevals = array('daughter', 'she', 'her', 'girl');
$malestr = str_replace($placeholders, $malevals, $rawstring);
$femalestr = str_replace($placeholders, $femalevals, $rawstring);
echo "Son: ". $malestr . "<br />";
echo "Daughter: ". $femalestr;



Output for last but statement:
Son: Welcome Birmingham parent!
Your son is a pleasure to have! We believe he is learning a lot.
The faculty simple adores he2 and you can often hear them say "Attah boy!"
                Jul 2012
                 Jan 2013                                                                © 2012 UPES
Comparing Arrays to Each other
  You can find difference between two arrays using the array_diff
   function.
         $ice_cream1 = array(“vanilla”, “chocolate”, “strawberry”);
         $ice_cream2 = aray(“vanilla”, “chocolate”, “papaya”);
         $diff = array_diff($ice_cream1, $ice_cream2);
         foreach($diff as $key => $value)
         {
                         echo “key : $key; value: $value n”;
         }
 Output:
 Key : 2; value : strawberry

             Jul 2012
              Jan 2013                                                © 2012 UPES
Jul 2012
 Jan 2013   © 2012 UPES

More Related Content

What's hot

Java 8-streams-collectors-patterns
Java 8-streams-collectors-patternsJava 8-streams-collectors-patterns
Java 8-streams-collectors-patterns
José Paumard
 
sets and maps
 sets and maps sets and maps
sets and maps
Rajkattamuri
 
Php with MYSQL Database
Php with MYSQL DatabasePhp with MYSQL Database
Php with MYSQL Database
Computer Hardware & Trouble shooting
 
Unirest Java Tutorial | Java Http Client
Unirest Java Tutorial | Java Http ClientUnirest Java Tutorial | Java Http Client
Unirest Java Tutorial | Java Http Client
rahul patel
 
07 java collection
07 java collection07 java collection
07 java collection
Abhishek Khune
 
Php Tutorials for Beginners
Php Tutorials for BeginnersPhp Tutorials for Beginners
Php Tutorials for Beginners
Vineet Kumar Saini
 
Introduction To Catalyst - Part 1
Introduction To Catalyst - Part 1Introduction To Catalyst - Part 1
Introduction To Catalyst - Part 1
Dan Dascalescu
 
Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2
José Paumard
 
Introduction to Perl - Day 2
Introduction to Perl - Day 2Introduction to Perl - Day 2
Introduction to Perl - Day 2Dave Cross
 
Broadleaf Presents Thymeleaf
Broadleaf Presents ThymeleafBroadleaf Presents Thymeleaf
Broadleaf Presents Thymeleaf
Broadleaf Commerce
 
PHP - Introduction to PHP Cookies and Sessions
PHP - Introduction to PHP Cookies and SessionsPHP - Introduction to PHP Cookies and Sessions
PHP - Introduction to PHP Cookies and Sessions
Vibrant Technologies & Computers
 
Java 9 Features
Java 9 FeaturesJava 9 Features
Java 9 Features
NexThoughts Technologies
 
Java script ppt
Java script pptJava script ppt
Collections - Maps
Collections - Maps Collections - Maps
Collections - Maps
Hitesh-Java
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8
Knoldus Inc.
 
Spring jdbc
Spring jdbcSpring jdbc
Spring jdbc
Harshit Choudhary
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
Sony India Software Center
 
Sql query patterns, optimized
Sql query patterns, optimizedSql query patterns, optimized
Sql query patterns, optimized
Karwin Software Solutions LLC
 
Form Handling using PHP
Form Handling using PHPForm Handling using PHP
Form Handling using PHP
Nisa Soomro
 

What's hot (20)

Java 8-streams-collectors-patterns
Java 8-streams-collectors-patternsJava 8-streams-collectors-patterns
Java 8-streams-collectors-patterns
 
sets and maps
 sets and maps sets and maps
sets and maps
 
Php with MYSQL Database
Php with MYSQL DatabasePhp with MYSQL Database
Php with MYSQL Database
 
Unirest Java Tutorial | Java Http Client
Unirest Java Tutorial | Java Http ClientUnirest Java Tutorial | Java Http Client
Unirest Java Tutorial | Java Http Client
 
07 java collection
07 java collection07 java collection
07 java collection
 
Php Tutorials for Beginners
Php Tutorials for BeginnersPhp Tutorials for Beginners
Php Tutorials for Beginners
 
Introduction To Catalyst - Part 1
Introduction To Catalyst - Part 1Introduction To Catalyst - Part 1
Introduction To Catalyst - Part 1
 
Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2
 
Introduction to Perl - Day 2
Introduction to Perl - Day 2Introduction to Perl - Day 2
Introduction to Perl - Day 2
 
Broadleaf Presents Thymeleaf
Broadleaf Presents ThymeleafBroadleaf Presents Thymeleaf
Broadleaf Presents Thymeleaf
 
PHP - Introduction to PHP Cookies and Sessions
PHP - Introduction to PHP Cookies and SessionsPHP - Introduction to PHP Cookies and Sessions
PHP - Introduction to PHP Cookies and Sessions
 
Java 9 Features
Java 9 FeaturesJava 9 Features
Java 9 Features
 
Java script ppt
Java script pptJava script ppt
Java script ppt
 
Collections - Maps
Collections - Maps Collections - Maps
Collections - Maps
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8
 
Spring jdbc
Spring jdbcSpring jdbc
Spring jdbc
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
 
Uploading a file with php
Uploading a file with phpUploading a file with php
Uploading a file with php
 
Sql query patterns, optimized
Sql query patterns, optimizedSql query patterns, optimized
Sql query patterns, optimized
 
Form Handling using PHP
Form Handling using PHPForm Handling using PHP
Form Handling using PHP
 

Viewers also liked

PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & Arrays
Henry Osborne
 
Arrays PHP 03
Arrays PHP 03Arrays PHP 03
Arrays PHP 03
Spy Seat
 
Php array
Php arrayPhp array
Php array
Nikul Shah
 
Php Using Arrays
Php Using ArraysPhp Using Arrays
Php Using Arraysmussawir20
 
PHP array 1
PHP array 1PHP array 1
PHP array 1
Mudasir Syed
 
Php.ppt
Php.pptPhp.ppt
Php.ppt
Nidhi mishra
 
Synapseindia reviews on array php
Synapseindia reviews on array phpSynapseindia reviews on array php
Synapseindia reviews on array php
saritasingh19866
 
03 Php Array String Functions
03 Php Array String Functions03 Php Array String Functions
03 Php Array String Functions
Geshan Manandhar
 
Array in php
Array in phpArray in php
Array in phpilakkiya
 
PHP Array very Easy Demo
PHP Array very Easy DemoPHP Array very Easy Demo
PHP Array very Easy Demo
Salman Memon
 
Web app development_php_06
Web app development_php_06Web app development_php_06
Web app development_php_06Hassen Poreya
 
How to Create an Array & types in PHP
How to Create an Array & types in PHP How to Create an Array & types in PHP
How to Create an Array & types in PHP
Ajit Sinha
 
Php array
Php arrayPhp array
Php array
argusacademy
 
PHP: Arrays
PHP: ArraysPHP: Arrays
PHP: Arrays
Mario Raul PEREZ
 
PHP Arrays
PHP ArraysPHP Arrays
PHP Arrays
Mahesh Gattani
 
Class 4 - PHP Arrays
Class 4 - PHP ArraysClass 4 - PHP Arrays
Class 4 - PHP Arrays
Ahmed Swilam
 
PHP Web Programming
PHP Web ProgrammingPHP Web Programming
PHP Web Programming
Muthuselvam RS
 

Viewers also liked (20)

Php array
Php arrayPhp array
Php array
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & Arrays
 
Arrays in PHP
Arrays in PHPArrays in PHP
Arrays in PHP
 
Arrays PHP 03
Arrays PHP 03Arrays PHP 03
Arrays PHP 03
 
Php array
Php arrayPhp array
Php array
 
Php Using Arrays
Php Using ArraysPhp Using Arrays
Php Using Arrays
 
PHP array 1
PHP array 1PHP array 1
PHP array 1
 
Php.ppt
Php.pptPhp.ppt
Php.ppt
 
Synapseindia reviews on array php
Synapseindia reviews on array phpSynapseindia reviews on array php
Synapseindia reviews on array php
 
My self learn -Php
My self learn -PhpMy self learn -Php
My self learn -Php
 
03 Php Array String Functions
03 Php Array String Functions03 Php Array String Functions
03 Php Array String Functions
 
Array in php
Array in phpArray in php
Array in php
 
PHP Array very Easy Demo
PHP Array very Easy DemoPHP Array very Easy Demo
PHP Array very Easy Demo
 
Web app development_php_06
Web app development_php_06Web app development_php_06
Web app development_php_06
 
How to Create an Array & types in PHP
How to Create an Array & types in PHP How to Create an Array & types in PHP
How to Create an Array & types in PHP
 
Php array
Php arrayPhp array
Php array
 
PHP: Arrays
PHP: ArraysPHP: Arrays
PHP: Arrays
 
PHP Arrays
PHP ArraysPHP Arrays
PHP Arrays
 
Class 4 - PHP Arrays
Class 4 - PHP ArraysClass 4 - PHP Arrays
Class 4 - PHP Arrays
 
PHP Web Programming
PHP Web ProgrammingPHP Web Programming
PHP Web Programming
 

Similar to PHP Unit 4 arrays

PHP tips and tricks
PHP tips and tricks PHP tips and tricks
PHP tips and tricks
Damien Seguy
 
Php tips-and-tricks4128
Php tips-and-tricks4128Php tips-and-tricks4128
Php tips-and-tricks4128PrinceGuru MS
 
Miniproject on Employee Management using Perl/Database.
Miniproject on Employee Management using Perl/Database.Miniproject on Employee Management using Perl/Database.
Miniproject on Employee Management using Perl/Database.
Sanchit Raut
 
Daily notes
Daily notesDaily notes
Daily notes
meghendra168
 
Array Methods.pptx
Array Methods.pptxArray Methods.pptx
Array Methods.pptx
stargaming38
 
Google Visualization API
Google  Visualization  APIGoogle  Visualization  API
Google Visualization API
Jason Young
 
Intermediate Perl
Intermediate PerlIntermediate Perl
Intermediate Perl
Dave Cross
 
PHP and MySQL Tips and tricks, DC 2007
PHP and MySQL Tips and tricks, DC 2007PHP and MySQL Tips and tricks, DC 2007
PHP and MySQL Tips and tricks, DC 2007
Damien Seguy
 
Chapter 2 wbp.pptx
Chapter 2 wbp.pptxChapter 2 wbp.pptx
Chapter 2 wbp.pptx
40NehaPagariya
 
Adventures in Optimization
Adventures in OptimizationAdventures in Optimization
Adventures in Optimization
David Golden
 
Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB jhchabran
 
Drupal Development (Part 2)
Drupal Development (Part 2)Drupal Development (Part 2)
Drupal Development (Part 2)
Jeff Eaton
 
Web 8 | Introduction to PHP
Web 8 | Introduction to PHPWeb 8 | Introduction to PHP
Web 8 | Introduction to PHP
Mohammad Imam Hossain
 
Why Hacking WordPress Search Isn't Some Big Scary Thing
Why Hacking WordPress Search Isn't Some Big Scary ThingWhy Hacking WordPress Search Isn't Some Big Scary Thing
Why Hacking WordPress Search Isn't Some Big Scary Thing
Chris Reynolds
 
Topological indices (t is) of the graphs to seek qsar models of proteins com...
Topological indices (t is) of the graphs  to seek qsar models of proteins com...Topological indices (t is) of the graphs  to seek qsar models of proteins com...
Topological indices (t is) of the graphs to seek qsar models of proteins com...
Jitendra Kumar Gupta
 
How to write code you won't hate tomorrow
How to write code you won't hate tomorrowHow to write code you won't hate tomorrow
How to write code you won't hate tomorrow
Pete McFarlane
 
R57shell
R57shellR57shell
R57shell
ady36
 
The Art of Transduction
The Art of TransductionThe Art of Transduction
The Art of Transduction
David Stockton
 

Similar to PHP Unit 4 arrays (20)

PHP tips and tricks
PHP tips and tricks PHP tips and tricks
PHP tips and tricks
 
Php tips-and-tricks4128
Php tips-and-tricks4128Php tips-and-tricks4128
Php tips-and-tricks4128
 
Miniproject on Employee Management using Perl/Database.
Miniproject on Employee Management using Perl/Database.Miniproject on Employee Management using Perl/Database.
Miniproject on Employee Management using Perl/Database.
 
Daily notes
Daily notesDaily notes
Daily notes
 
Array Methods.pptx
Array Methods.pptxArray Methods.pptx
Array Methods.pptx
 
Google Visualization API
Google  Visualization  APIGoogle  Visualization  API
Google Visualization API
 
Intermediate Perl
Intermediate PerlIntermediate Perl
Intermediate Perl
 
PHP and MySQL Tips and tricks, DC 2007
PHP and MySQL Tips and tricks, DC 2007PHP and MySQL Tips and tricks, DC 2007
PHP and MySQL Tips and tricks, DC 2007
 
Drupal7 dbtng
Drupal7  dbtngDrupal7  dbtng
Drupal7 dbtng
 
Chapter 2 wbp.pptx
Chapter 2 wbp.pptxChapter 2 wbp.pptx
Chapter 2 wbp.pptx
 
Adventures in Optimization
Adventures in OptimizationAdventures in Optimization
Adventures in Optimization
 
wget.pl
wget.plwget.pl
wget.pl
 
Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB
 
Drupal Development (Part 2)
Drupal Development (Part 2)Drupal Development (Part 2)
Drupal Development (Part 2)
 
Web 8 | Introduction to PHP
Web 8 | Introduction to PHPWeb 8 | Introduction to PHP
Web 8 | Introduction to PHP
 
Why Hacking WordPress Search Isn't Some Big Scary Thing
Why Hacking WordPress Search Isn't Some Big Scary ThingWhy Hacking WordPress Search Isn't Some Big Scary Thing
Why Hacking WordPress Search Isn't Some Big Scary Thing
 
Topological indices (t is) of the graphs to seek qsar models of proteins com...
Topological indices (t is) of the graphs  to seek qsar models of proteins com...Topological indices (t is) of the graphs  to seek qsar models of proteins com...
Topological indices (t is) of the graphs to seek qsar models of proteins com...
 
How to write code you won't hate tomorrow
How to write code you won't hate tomorrowHow to write code you won't hate tomorrow
How to write code you won't hate tomorrow
 
R57shell
R57shellR57shell
R57shell
 
The Art of Transduction
The Art of TransductionThe Art of Transduction
The Art of Transduction
 

More from Kumar

Graphics devices
Graphics devicesGraphics devices
Graphics devices
Kumar
 
Fill area algorithms
Fill area algorithmsFill area algorithms
Fill area algorithms
Kumar
 
region-filling
region-fillingregion-filling
region-filling
Kumar
 
Bresenham derivation
Bresenham derivationBresenham derivation
Bresenham derivation
Kumar
 
Bresenham circles and polygons derication
Bresenham circles and polygons dericationBresenham circles and polygons derication
Bresenham circles and polygons derication
Kumar
 
Introductionto xslt
Introductionto xsltIntroductionto xslt
Introductionto xslt
Kumar
 
Extracting data from xml
Extracting data from xmlExtracting data from xml
Extracting data from xml
Kumar
 
Xml basics
Xml basicsXml basics
Xml basics
Kumar
 
XML Schema
XML SchemaXML Schema
XML Schema
Kumar
 
Publishing xml
Publishing xmlPublishing xml
Publishing xml
Kumar
 
DTD
DTDDTD
DTD
Kumar
 
Applying xml
Applying xmlApplying xml
Applying xml
Kumar
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XML
Kumar
 
How to deploy a j2ee application
How to deploy a j2ee applicationHow to deploy a j2ee application
How to deploy a j2ee application
Kumar
 
JNDI, JMS, JPA, XML
JNDI, JMS, JPA, XMLJNDI, JMS, JPA, XML
JNDI, JMS, JPA, XML
Kumar
 
EJB Fundmentals
EJB FundmentalsEJB Fundmentals
EJB Fundmentals
Kumar
 
JSP and struts programming
JSP and struts programmingJSP and struts programming
JSP and struts programming
Kumar
 
java servlet and servlet programming
java servlet and servlet programmingjava servlet and servlet programming
java servlet and servlet programming
Kumar
 
Introduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC DriversIntroduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC Drivers
Kumar
 
Introduction to J2EE
Introduction to J2EEIntroduction to J2EE
Introduction to J2EE
Kumar
 

More from Kumar (20)

Graphics devices
Graphics devicesGraphics devices
Graphics devices
 
Fill area algorithms
Fill area algorithmsFill area algorithms
Fill area algorithms
 
region-filling
region-fillingregion-filling
region-filling
 
Bresenham derivation
Bresenham derivationBresenham derivation
Bresenham derivation
 
Bresenham circles and polygons derication
Bresenham circles and polygons dericationBresenham circles and polygons derication
Bresenham circles and polygons derication
 
Introductionto xslt
Introductionto xsltIntroductionto xslt
Introductionto xslt
 
Extracting data from xml
Extracting data from xmlExtracting data from xml
Extracting data from xml
 
Xml basics
Xml basicsXml basics
Xml basics
 
XML Schema
XML SchemaXML Schema
XML Schema
 
Publishing xml
Publishing xmlPublishing xml
Publishing xml
 
DTD
DTDDTD
DTD
 
Applying xml
Applying xmlApplying xml
Applying xml
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XML
 
How to deploy a j2ee application
How to deploy a j2ee applicationHow to deploy a j2ee application
How to deploy a j2ee application
 
JNDI, JMS, JPA, XML
JNDI, JMS, JPA, XMLJNDI, JMS, JPA, XML
JNDI, JMS, JPA, XML
 
EJB Fundmentals
EJB FundmentalsEJB Fundmentals
EJB Fundmentals
 
JSP and struts programming
JSP and struts programmingJSP and struts programming
JSP and struts programming
 
java servlet and servlet programming
java servlet and servlet programmingjava servlet and servlet programming
java servlet and servlet programming
 
Introduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC DriversIntroduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC Drivers
 
Introduction to J2EE
Introduction to J2EEIntroduction to J2EE
Introduction to J2EE
 

Recently uploaded

How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
EduSkills OECD
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Po-Chuan Chen
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Atul Kumar Singh
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 

Recently uploaded (20)

How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 

PHP Unit 4 arrays

  • 1. UNIT – 4 ARRAYS Dr. P S V S Sridhar Assistant Professor (SS) Centre for Information Technology | Jan 2013| © 2012 UPES
  • 2. Introduction to Array -An array can store one or more values in a single variable name. -Each element in the array is assigned its own ID so that it can be easily accessed. -$array[key] = value; $arrayname[]=value array() language construct Jul 2012 Jan 2013 © 2012 UPES
  • 3. Array in PHP 1) Numeric Array 2) Associative Array 3) Multidimensional Array Jul 2012 Jan 2013 © 2012 UPES
  • 4. Numeric Array - A numeric array stores each element with a numeric ID key. - 2 ways to write a numeric array. 1. Automatically Example: $names = array("Peter","Quagmire","Joe"); 2. Manually Example1: $names[0] = "Peter"; $names[1] = "Quagmire"; $names[2] = "Joe"; Example 2: $name[] =”Peter”; $name[] =“Quagmire”; $name[] = “joe”; In the above case we are adding sequential elements that should have numerical counting upward from zero. Jul 2012 Jan 2013 © 2012 UPES
  • 5. Associative Arrays -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. Example: Using an array to assign an age to a person. $ages = array(”Brent"=>42, ”Andrew"=>25, "Joshua”=>16); $ages[‟Brent'] = 42; $ages[‟Andrew'] = 25; $ages['Joshua'] = 16; Eamample: $f = array(0=>”apple”, 1=>”orange”, 2=>”banana”, 3=>”pear”); In the above example index values are 0,1,2,3 Jul 2012 Jan 2013 © 2012 UPES
  • 6. Array creation:  following creates an array with numeric index  $icecream_menu=array(275,160,290,250); which is equivalent to the following array creation $icecream_menu=array(0=>275,1=>160,2=>290,3=>250);  Arrays can be created with other scalar values as well as mix of them  $icecream_menu1[-1]=275; $icecream_menu1[„item 2‟]=160; $icecream_menu1[3.4]=290; $icecream_menu1[false]=250;  An array with a mix of all values can also be created $icecream_menu=array(-1=>275,'item 2'=>160,3.4=>290,false=>250); Jul 2012 Jan 2013 © 2012 UPES
  • 7. Creating an Empty Array  $marks=array(); Jul 2012 Jan 2013 © 2012 UPES
  • 8. Finding the Size of an Array  The count() function is used to find the number of elements in the array  $icecream_menu=array('Almond Punch'=>275,'Nutty Crunch'=>160,'Choco Dip'=>290,'Oreo Cherry'=>250); print "There are ".count($icecream_menu) ." flavours of icecreams available!!"  prints the following  There are 4 flavours of icecreams available!! Jul 2012 Jan 2013 © 2012 UPES
  • 9. Printing an Array in a readable way  The print_r() ,when passed an array, prints its contents in a readable way.  $icecream_menu=array('Almond Punch'=>275,'Nutty Crunch'=>160,'Choco Dip'=>290,'Oreo Cherry'=>250);  print_r($icecream_menu);  Output of the above code will be Array ( [Almond Punch] => 275 [Nutty Crunch] => 160 [Choco Dip] => 290 [Oreo Cherry] => 250 ) Jul 2012 Jan 2013 © 2012 UPES
  • 10. Iterating Array Elements  The easiest way to iterate through each element of an array is with foreach(). The foreach()construct executes the block of code once for each element in an array.  Syntax  foreach($array as [$key =>] [&] $value) { //block of code to be executed for each iteration }  $array – represents the array to be iterated  $key is optional, and when specified, it contains the currently iterated array value‟s key, which can be any scalar value, depending on the key‟s type.  $value holds the array value, for the given $key value.  Using the & for the $value, indicates that any change made in the $value variable while iteration will be reflected in the original array($array) also. Jul 2012 Jan 2013 © 2012 UPES
  • 11. Modifying Array while iteration  Arrays can be modified during iteration in 2 ways.  Direct Array Modification  Indirect Array Modification Jul 2012 Jan 2013 © 2012 UPES
  • 12. Direct Array Modification  Say for example we need to increase the price of the all icecreams by 50 .The following code helps us to update the price and display the revised price along with the old ones  <html> <body> <h3 align="center"><i>Chillers...</i></h3> <table align="center"> <tr bgcolor="#D7D7D7" ><td >Icecream Flavours</td><td>Price</td></tr> <?php $icecream_menu=array('Almond Punch'=>275,'Nutty Crunch'=>160,'Choco Dip'=>290,'Oreo Cherry'=>250); foreach($icecream_menu as $key=>$value) { print "<tr bgcolor='#F3F3F3'>"; print "<td>".$key."</td><td>".$value."</td>"; print "</tr>"; } ?> </table> <h3 align="center"><i>Chillers Revised Price.....</i></h3> <table align="center"> <tr bgcolor="#D7D7D7" ><td >Icecream Flavours</td><td>Price</td></tr> Jul 2012 Jan 2013 © 2012 UPES
  • 13. Contd…  <?php foreach($icecream_menu as $key=>&$value) { //increase the price of all icecreams by 50 $icecream_menu[$key]=$value+50; $value=$icecream_menu[$key]; print "<tr bgcolor='#F3F3F3'>"; print "<td>".$key."</td><td>".$value."</td>"; print "</tr>"; } ?> </table> </body> </html> Jul 2012 Jan 2013 © 2012 UPES
  • 14. Indirect Array Modification  foreach($array as [$key =>] [&] $value) { //block of code to be executed for each iteration }  where “&‟ can be used with $value.Any change in $value,indirectly modifies the value of the array for the current key during the iteration.  foreach($icecream_menu as $key=>&$value) { //increase the price of all icecreams by 50 $value=$value+50; print "<tr bgcolor='#F3F3F3'>"; print "<td>".$key."</td><td>".$value."</td>"; print "</tr>"; } Jul 2012 Jan 2013 © 2012 UPES
  • 15. Iterating Array with Numeric index  Arrays with numeric index can be accessed using  foreach() and for() Ex1:  $hobbies=array("Reading Books","Playing Golf","Watching Tennis","Dancing"); foreach($hobbies as $hobby) { print "<br> $hobby "; } Ex 2:  for($i=0,$arraysize=count($hobbies);$i<$arraysize;$i++) print "<br> $hobbies[$i]"; Jul 2012 Jan 2013 © 2012 UPES
  • 16. Multi dimensional Arrays - In a multidimensional array, each element in the main array can also be an array. - And each element in the sub-array can be an array, and so on. Ex1: $families = array ("Griffin"=>array ( "Peter","Lois", "Megan" ), "Quagmire"=>array ( "Glenn" ), "Brown"=>array ("Cleveland", "Loretta", "Junior" ) ); Ex2: $icecream_menu=array('Almond Punch'=>array("single"=>275,"couple"=>425,"family"=>500), 'Nutty Crunch'=>array("couple"=>375,"family"=>450), 'Choco Dip'=>array("single"=>275,"Treat"=>425,"family"=>600), 'Oreo Cherry'=>array("single"=>450,"family"=>525)); Jul 2012 Jan 2013 © 2012 UPES
  • 17. Handling Multidimensional arrays $scores[“sam”][1] = 79; $scores[“sam”][2] = 74; $scores[“ellen”][1] = 69; $scores[“ellen”][2] = 84; Print_r($scores); Output: [sam] => array([1] =>79 [2] =>74 ) [ellen] => array([1] => 69 [2] => 84 ) Jul 2012 Jan 2013 © 2012 UPES
  • 18. Handling Multidimensional arrays Ex: $scores[“sam”][] = 79; $scores[“sam”][] = 74; $scores[“ellen”][] = 69; $scores[“ellen”][] = 84; Here index start from 0. Ex: $scores = array(“sam” => array(79,74), “ellen” => array(69,84)); Jul 2012 Jan 2013 © 2012 UPES
  • 19. Multi dimensional arrays in loops $scores[0][] = 79; $scores[0][] = 74; $scores[1][] = 69; $scores[1][] = 84; for($outer = 0; $outer < count($scores); $outer++) for($inner = 0; $inner < count($scores[$outer]); $inner++) { echo $scores[$outer][$inner]; } Jul 2012 Jan 2013 © 2012 UPES
  • 20. Splitting and Merging Arrays array_slice function will split array Ex1: $ice_cream[“good”] = “orange”; $ice_cream[“better”] = “vanilla”; $ice_cream[“best”] = “rum raisin”; $ice_cream[“bestest”] = “lime”; $subarray = array_slice($ice_cream, 1,2);  The index value of better and best will be stored in $subarray as vanilla rum raisin Ex2: <?php $input = array("a", "b", "c", "d", "e"); $output = array_slice($input, 2); // returns "c", "d", and "e" $output = array_slice($input, -2, 1); // returns "d" $output = array_slice($input, 0, 3); // returns "a", "b", and "c“ ?> Jul 2012 Jan 2013 © 2012 UPES
  • 21. Splitting and Merging Arrays array_merge will merge the arrays Ex1: $pudding = array(“vanilla”, “run raisin”, “orange”); $ice_cream = array(“chocolate”,”pecan”,”strawberry”); $desserts = array_merge($pudding, $ice_cream); The elements of $pudding and $ice_cream will be stored in $desserts array. Ex2: <?php $array1 = array("color" => "red", 2, 4); $array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4); $result = array_merge($array1, $array2); print_r($result); ?> Output: Array ( [color] => green [0] => 2 [1] => 4 [2] => a [3] => b [shape] => trapezoid [4] => 4 ) © 2012 UPES Jul 2012 Jan 2013
  • 22. Sorting of Arrays  Sort - Sorts the array values (loses key) <?php $fruits = array("lemon", "orange", "banana", "apple"); sort($fruits); foreach ($fruits as $key => $val) { echo "fruits[" . $key . "] = " . $val . "n"; } ?> Output: fruits[0] = apple fruits[1] = banana fruits[2] = lemon fruits[3] = orange Jul 2012 Jan 2013 © 2012 UPES
  • 23. Sorting of Arrays  Ksort - Sorts the array by key along with value <?php $fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple"); ksort($fruits); foreach ($fruits as $key => $val) { echo "$key = $valn"; } ?> Output: a = orange b = banana c = apple d = lemon Jul 2012 Jan 2013 © 2012 UPES
  • 24. Sorting of Arrays  asort - Sorts array by value, keeping key association <?php $fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple"); asort($fruits); foreach ($fruits as $key => $val) { echo "$key = $valn"; } ?> Output: c = apple b = banana d = lemon a = orange Jul 2012 Jan 2013 © 2012 UPES
  • 25. Array functions  count($ar) - How many elements in an array  array_sum($ar) – sum of array values.  sizeof($ar) – Identical to count()  is_array($ar) - Returns TRUE if a variable is an array  sort($ar) - Sorts the array values (loses key)  ksort($ar) - Sorts the array by key along with value  asort($ar) - Sorts array by value, keeping key association  shuffle($ar) - Shuffles the array into random order  $a = array() – Creates an array $a with no elements  $a = range(1,5) – Create an array between 1 and 5. i.e., $a = array(1,2,3,4,5)  in_array() – Takes two arguments: an element and an array. Returns true if the element contained as a value in the array.  rsort(), arsort(), krsort() - Works similar to sort(), asort() and ksort() except that they sort the array in descending order Jul 2012 Jan 2013 © 2012 UPES
  • 26. Array functions  list():  Assign array values to variable.  Ex: $f = array(„apple‟,‟orange‟,‟banana‟);  list($r,$o) = $f;  The string apple is assigned to $r and orange is assigned to $o and no assignment of string banana.  reset():  Gives us a way to “rewind” that pointer to the beginning – it sets the pointer to the first key/value pair and then returned to stored value.  next():  which moves the current pointer ahead by one,  prev():  Which moves the pointer back by one.  current():  Returns the current element in an array  end()  Which moves2012 end of the array Jul to Jan 2013 © 2012 UPES
  • 27. Next, current, Prev  <?php $array = array('step one', 'step two', 'step three', 'step four'); // by default, the pointer is on the first element echo current($array) . "<br />n"; // "step one" // skip two steps next($array); next($array); echo current($array) . "<br />n"; // "step three" // reset pointer, start again on step one reset($array); echo current($array) . "<br />n"; // "step one" ?> Jul 2012 Jan 2013 © 2012 UPES
  • 28. Array functions  Deleting from arrays: Just call unset()  $a[0] = “wanted”;  $a[1]=“unwanted”;  $a[2]=“wanted again”;  unset($a[1]);  Deletes 1 key value. Now the above array contains two key values (0,2) Jul 2012 Jan 2013 © 2012 UPES
  • 29. Extracting Data from Arrays  Extract function to extract data from arrays and store it in variable. $ice_cream[“good”] = “orange”; $ice_cream[“better”] = “vanilla”; $ice_cream[“best”] = “rum raisin”; extract($ice_cream); echo “$good = $good <br>”; echo “$better = $better <br>”; echo “$best = $best <br>”; Output: $good = orange $better = vanilla $best = rum raisin Jul 2012 Jan 2013 © 2012 UPES
  • 30. Arrays and Strings explode(): The function explode converts string into array format . We can use explode() to split a string into an array of strings $inp = "This is a sentence with seven words"; $temp = explode(‘ ', $inp); print_r($temp); Output: Array( [0] => This [1] => is [2] => a [3] => sentence [4] => with [5] => seven [6] => words) implode(): To combine array of elements in to a string  $p = array("Hello", "World,", "I", "am", "Here!");  $g = implode(" ", $p);  Output: Hello World I am Here Jul 2012 Jan 2013 © 2012 UPES
  • 31. Arrays and strings  str_replace(): $rawstring = "Welcome Birmingham parent! <br /> Your offspring is a pleasure to have! We believe pronoun is learning a lot.<br />The faculty simple adores pronoun2 and you can often hear them say "Attah sex!"<br />"; $placeholders = array('offspring', 'pronoun', 'pronoun2', 'sex'); $malevals = array('son', 'he', 'him', 'boy'); $femalevals = array('daughter', 'she', 'her', 'girl'); $malestr = str_replace($placeholders, $malevals, $rawstring); $femalestr = str_replace($placeholders, $femalevals, $rawstring); echo "Son: ". $malestr . "<br />"; echo "Daughter: ". $femalestr; Output for last but statement: Son: Welcome Birmingham parent! Your son is a pleasure to have! We believe he is learning a lot. The faculty simple adores he2 and you can often hear them say "Attah boy!" Jul 2012 Jan 2013 © 2012 UPES
  • 32. Comparing Arrays to Each other  You can find difference between two arrays using the array_diff function. $ice_cream1 = array(“vanilla”, “chocolate”, “strawberry”); $ice_cream2 = aray(“vanilla”, “chocolate”, “papaya”); $diff = array_diff($ice_cream1, $ice_cream2); foreach($diff as $key => $value) { echo “key : $key; value: $value n”; } Output: Key : 2; value : strawberry Jul 2012 Jan 2013 © 2012 UPES
  • 33. Jul 2012 Jan 2013 © 2012 UPES