SlideShare uma empresa Scribd logo
1 de 33
Baixar para ler offline
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

Mais conteúdo relacionado

Mais procurados

PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & ArraysHenry Osborne
 
PHP Frameworks and CodeIgniter
PHP Frameworks and CodeIgniterPHP Frameworks and CodeIgniter
PHP Frameworks and CodeIgniterKHALID C
 
PHP Cookies and Sessions
PHP Cookies and SessionsPHP Cookies and Sessions
PHP Cookies and SessionsNisa Soomro
 
Form Handling using PHP
Form Handling using PHPForm Handling using PHP
Form Handling using PHPNisa Soomro
 
Introduction to Perl - Day 1
Introduction to Perl - Day 1Introduction to Perl - Day 1
Introduction to Perl - Day 1Dave Cross
 
Form Processing In Php
Form Processing In PhpForm Processing In Php
Form Processing In PhpHarit Kothari
 
PHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object CalisthenicsPHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object CalisthenicsGuilherme Blanco
 
Node.js Event Emitter
Node.js Event EmitterNode.js Event Emitter
Node.js Event EmitterEyal Vardi
 
FS_module_functions.pptx
FS_module_functions.pptxFS_module_functions.pptx
FS_module_functions.pptxBareen Shaikh
 
PHP Form Validation Technique
PHP Form Validation TechniquePHP Form Validation Technique
PHP Form Validation TechniqueMorshedul Arefin
 
JavaScript Arrays
JavaScript Arrays JavaScript Arrays
JavaScript Arrays Reem Alattas
 

Mais procurados (20)

Php string function
Php string function Php string function
Php string function
 
Day01 api
Day01   apiDay01   api
Day01 api
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & Arrays
 
PHP Frameworks and CodeIgniter
PHP Frameworks and CodeIgniterPHP Frameworks and CodeIgniter
PHP Frameworks and CodeIgniter
 
PHP and Mysql
PHP and MysqlPHP and Mysql
PHP and Mysql
 
PHP Cookies and Sessions
PHP Cookies and SessionsPHP Cookies and Sessions
PHP Cookies and Sessions
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHP
 
Form Handling using PHP
Form Handling using PHPForm Handling using PHP
Form Handling using PHP
 
Introduction to Perl - Day 1
Introduction to Perl - Day 1Introduction to Perl - Day 1
Introduction to Perl - Day 1
 
Arrays in php
Arrays in phpArrays in php
Arrays in php
 
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
 
Php session
Php sessionPhp session
Php session
 
Introdução APIs RESTful
Introdução APIs RESTfulIntrodução APIs RESTful
Introdução APIs RESTful
 
Form Processing In Php
Form Processing In PhpForm Processing In Php
Form Processing In Php
 
Php array
Php arrayPhp array
Php array
 
PHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object CalisthenicsPHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object Calisthenics
 
Node.js Event Emitter
Node.js Event EmitterNode.js Event Emitter
Node.js Event Emitter
 
FS_module_functions.pptx
FS_module_functions.pptxFS_module_functions.pptx
FS_module_functions.pptx
 
PHP Form Validation Technique
PHP Form Validation TechniquePHP Form Validation Technique
PHP Form Validation Technique
 
JavaScript Arrays
JavaScript Arrays JavaScript Arrays
JavaScript Arrays
 

Destaque (19)

Php array
Php arrayPhp array
Php array
 
Arrays in PHP
Arrays in PHPArrays in PHP
Arrays in PHP
 
Arrays in PHP
Arrays in PHPArrays in PHP
Arrays in PHP
 
Arrays PHP 03
Arrays PHP 03Arrays PHP 03
Arrays PHP 03
 
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
 

Semelhante a 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
 
Array Methods.pptx
Array Methods.pptxArray Methods.pptx
Array Methods.pptxstargaming38
 
Google Visualization API
Google  Visualization  APIGoogle  Visualization  API
Google Visualization APIJason Young
 
Intermediate Perl
Intermediate PerlIntermediate Perl
Intermediate PerlDave 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 2007Damien Seguy
 
Adventures in Optimization
Adventures in OptimizationAdventures in Optimization
Adventures in OptimizationDavid 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
 
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 ThingChris 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 tomorrowPete McFarlane
 
R57shell
R57shellR57shell
R57shellady36
 
The Art of Transduction
The Art of TransductionThe Art of Transduction
The Art of TransductionDavid Stockton
 

Semelhante a 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
 

Mais de Kumar

Graphics devices
Graphics devicesGraphics devices
Graphics devicesKumar
 
Fill area algorithms
Fill area algorithmsFill area algorithms
Fill area algorithmsKumar
 
region-filling
region-fillingregion-filling
region-fillingKumar
 
Bresenham derivation
Bresenham derivationBresenham derivation
Bresenham derivationKumar
 
Bresenham circles and polygons derication
Bresenham circles and polygons dericationBresenham circles and polygons derication
Bresenham circles and polygons dericationKumar
 
Introductionto xslt
Introductionto xsltIntroductionto xslt
Introductionto xsltKumar
 
Extracting data from xml
Extracting data from xmlExtracting data from xml
Extracting data from xmlKumar
 
Xml basics
Xml basicsXml basics
Xml basicsKumar
 
XML Schema
XML SchemaXML Schema
XML SchemaKumar
 
Publishing xml
Publishing xmlPublishing xml
Publishing xmlKumar
 
Applying xml
Applying xmlApplying xml
Applying xmlKumar
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XMLKumar
 
How to deploy a j2ee application
How to deploy a j2ee applicationHow to deploy a j2ee application
How to deploy a j2ee applicationKumar
 
JNDI, JMS, JPA, XML
JNDI, JMS, JPA, XMLJNDI, JMS, JPA, XML
JNDI, JMS, JPA, XMLKumar
 
EJB Fundmentals
EJB FundmentalsEJB Fundmentals
EJB FundmentalsKumar
 
JSP and struts programming
JSP and struts programmingJSP and struts programming
JSP and struts programmingKumar
 
java servlet and servlet programming
java servlet and servlet programmingjava servlet and servlet programming
java servlet and servlet programmingKumar
 
Introduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC DriversIntroduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC DriversKumar
 
Introduction to J2EE
Introduction to J2EEIntroduction to J2EE
Introduction to J2EEKumar
 

Mais de 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
 

Último

Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfChris Hunter
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.MateoGardella
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 

Último (20)

Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 

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