SlideShare a Scribd company logo
Using Arrays
Introduction Programming languages use variables to store values An array is a variable that can store a list of values Arrays can be single-dimensional or multidimensional All the values are referred by the same array name
Defining an Array An array is a complex variable that allows you to store multiple values in a single variable (which is handy when you need to store and represent related information).  An array is a variable that can store a set values of the same data type An array index is used to access an element
Indexed Array Example <?php  // define an array $pizzaToppings  = array( 'onion' ,  'tomato' ,  'cheese' ,  'anchovies' ,  'ham' ,  'pepperoni' );  print_r ( $pizzaToppings );  ?>  //Output Array ( [0] => onion [1] => tomato [2] => cheese  [3] => anchovies [4] => ham [5] => pepperoni )
Associative Arrays An associative array is an array where the index type is string PHP also allows you to replace indices with user-defined &quot;keys&quot;, in order to create a slightly different type of array.  Each key is unique, and corresponds to a single value within the array
Associative Arrays Example <?php  // define an array $fruits  = array( 'red'  =>  'apple' ,  'yellow'  =>  'banana' ,  'purple'  =>  'plum' ,  'green'  =>  'grape' );  print_r ( $fruits );  ?>  //Output Array ( [red] => apple [yellow] => banana [purple] => plum [green] => grape )
Define an Array The simplest was to define an array variable is the array() function  Example; <?php  // define an array $pasta = array('spaghetti', 'penne', 'macaroni');  ?>  Can define an array by specifying values for each element in the index notation  Example; <?php  // define an array $pasta [ 0 ] =  'spaghetti' ;  $pasta [ 1 ] =  'penne' ;  $pasta [ 2 ] =  'macaroni' ;  ?>
Define an Array Also can define an array by using keys rather than default numeric indices   Example; <?php  // define an array $menu [ 'breakfast' ] =  'bacon and eggs' ;  $menu [ 'lunch' ] =  'roast beef' ;  $menu [ 'dinner' ] =  'lasagna' ;  ?>
Modify an Array Add an element to an array Can add elements to the array in a similar manner  Also can modify the element by replace ‘anchovies ‘ with    'green olives';  Example; <?php  // add an element to an array $pizzaToppings [ 3 ] =  'green olives' ;  ?>
Push And Pull Adding an element to the end of existing array with the array_push() function; Example; <?php  // define an array $pasta  = array( 'spaghetti' ,  'penne' ,  'macaroni' );  // add an element to the end  array_push ( $pasta ,  'tagliatelle' );  print_r ( $pasta );  ?>  //Output Array ( [0] => spaghetti [1] => penne [2] => macaroni [3] => tagliatelle )
Push And Pull Adding an element to the beginning of existing array with the array_unshift() function; Example; <?php  // define an array $pasta  = array( 'spaghetti' ,  'penne' ,  'macaroni' );  // add an element to the end  array_unshift ( $pasta ,  'tagliatelle' );  print_r ( $pasta );  ?>  //Output Array ( [0] => tagliatelle [1] => spaghetti [2] => penne  [3] => macaroni
Push And Pull Removing  an element from the end of an array using the interestingly-named array_pop() function.  Example; <?php  // define an array $pasta  = array( 'spaghetti' ,  'penne' ,  'macaroni' );  // remove an element from the end  array_pop ( $pasta );  print_r ( $pasta );  ?>  //Output Array ( [0] => spaghetti [1] => penne )
Push And Pull Removing  an element from the top of an array using the interestingly-named array_shift() function.  Example; <?php  // define an array $pasta  = array( 'spaghetti' ,  'penne' ,  'macaroni' );  // remove an element from the top  array_shift ( $pasta );  print_r ( $pasta );  ?>  //Output Array ( [0] => penne[1] => macaroni )
Split a String The explode() function splits a string into smaller components, based on a user-specified delimiter, and returns the pieces as elements as an array.  Example; <?php  // define CSV string $str  =  'red, blue, green, yellow' ;  // split into individual words  $colors  =  explode ( ', ' ,  $str );  print_r ( $colors );  ?>  //Output Array ( [0] => red [1] => blue [2] => green [3] => yellow )
Split a String The implode() function can  creates a single string from all the elements of an array by joining them together with a user-defined delimiter.  Example; <?php  // define array $colors  = array ( 'red' ,  'blue' ,  'green' ,  'yellow' );  // join into single string with 'and'  // returns 'red and blue and green and yellow'  $str  =  implode ( ' and ' ,  $colors );  print  $str ;  ?>  //Output red and blue and green and yellow
Sorting sort() The sort() function arranges the element  values into an alphabetical order(Ascending) Example; <?php  // define an array $pasta  = array( 'spaghetti' ,  'penne' ,  'macaroni' );  // returns the array sorted alphabetically  sort ( $pasta );  print_r ( $pasta );   ?>   //Output Array ( [0] => macaroni [1] => penne [2] => spaghetti )
Sorting rsort() The rsort() function sort the element  values into the descending alphabetical order Example; <?php  // define an array $pasta  = array( 'spaghetti' ,  'penne' ,  'macaroni' );  // returns the array sorted alphabetically  rsort ($pasta);  print_r ( $pasta );   ?>   //Output Array ( [0] => spaghetti [1] => penne [2] => macaroni )
Looping the Loop  We can  read an entire array by  simply loop over it, using any of the loop constructs. Example; <?php  // define array  $artists  = array( 'Metallica' ,  'Evanescence' ,  'Linkin Park' ,  'Guns n Roses' );  // loop over it and print array elements  for ( $x  =  0 ;  $x  <  sizeof ( $artists );  $x ++) {      echo  '<li>' . $artists [ $x ];  }  ?>  //Output Metallica  Evanescence  Linkin Park  Guns n Roses
Looping the Loop The sizeof() function is one of the most important and commonly used array functions.  It returns the size of (read: number of elements within) the array.  It is mostly used in loop counters to ensure that the loop iterates as many times as there are elements in the array.  By  using an associative array, the array_keys() and array_values()functions come in handy, to get a list of all the keys and values within the array.
Looping the Loop There is a simpler way of extracting all the elements of an array by using foreach() loop.  A foreach() loop runs once for each element of the array passed to it as argument, moving forward through the array on each iteration.   Unlike a for() loop, it doesn't need a counter or a call to sizeof(), because it keeps track of its position in the array automatically. On each run, the statements within the curly braces are executed, and the currently-selected array element is made available through a temporary loop variable.   Example;  <?php  // define array  $artists  = array( 'Metallica' ,  'Evanescence' ,  'Linkin Park' ,  'Guns n Roses' );  // loop over it  // print array elements  foreach ( $artists  as  $a ) {      echo  '<li>' . $a ;  }  ?>
Looping the Loop Continue //Output Metallica  Evanescence  Linkin Park  Guns n Roses Each time the loop executes, it places the currently-selected array element in the temporary variable $a.  This variable can then be used by the statements inside the loop block foreach() loop doesn't need a counter to keep track of where it is in the array  Much easier to read than a standard for() loop .
Array And Loops Arrays and loops also come in handy when processing forms in PHP For example, if want to have a group of related checkboxes or a multi-select list, just use an array to capture all the selected form values in a single variable, to simplify processing  Example;
Array And Loops <?php  if (!isset( $_POST [ 'submit' ])) {       // and display form       ?>      <form action=&quot; <?php  echo  $_SERVER [ 'PHP_SELF' ];  ?> &quot; method=&quot;POST&quot;>      <input type=&quot;checkbox&quot; name=&quot;artist[]&quot; value=&quot;Bon Jovi&quot;>Bon Jovi      <input type=&quot;checkbox&quot; name=&quot;artist[]&quot; value=&quot;N'Sync&quot;>N'Sync      <input type=&quot;checkbox&quot; name=&quot;artist[]&quot; value=&quot;Boyzone&quot;>Boyzone      <input type=&quot;submit&quot; name=&quot;submit&quot; value=&quot;Select&quot;>      </form>  <?php       }  else {       // or display the selected artists      // use a foreach loop to read and display array elements       if ( is_array ( $_POST [ 'artist' ])) {          echo  'You selected: <br />' ;          foreach ( $_POST [ 'artist' ] as  $a ) {             echo  &quot;<i>$a</i><br />&quot; ;              }          }      else {          echo  'Nothing selected' ;      }  }  ?>  //Output You selected:  N\'Sync Boyzone
Multidimensional Array
Associative Multidimensional Array <?php $products = array( array( 'TIR', 'Tires', 100 ), array( 'OIL', 'Oil', 10 ), array( 'SPK','Spark Plugs', 4 ) );  for ( $row = 0; $row < 3; $row++ ) {  for ( $column = 0; $column < 3; $column++ ) {  echo '|'.$products[$row][$column]; }  echo '|<br/>';  }  ?>
Array Manipulations each() function Returns the current key and value pair from the array  array  and advances the array cursor. This pair is returned in a four-element array, with the keys 0, 1, key, and value. Elements 0 and key contain the key name of the array element, and 1 and value contain the data.  <?php $fruit  = array( 'a'  =>  'apple' ,  'b'  =>  'banana' ,  'c'  =>  'cranberry' ); reset ( $fruit ); while (list( $key ,  $val ) =  each ( $fruit )) {    echo  &quot;$key => $val\n&quot; ; } ?> The above example will output: copy to clipboard a => apple b => banana c => cranberry
<?php $array  = array( 'step one' ,  'step two' ,  'step three' ,  'step four' );   // by default, the pointer is on the first element   echo  current ( $array ) .  &quot;<br />\n&quot; ;  // &quot;step one&quot; // skip two steps     next ( $array );                                  next ( $array ); echo  current ( $array ) .  &quot;<br />\n&quot; ;  // &quot;step three&quot;   // reset pointer, start again on step one reset ( $array ); echo  current ( $array ) .  &quot;<br />\n&quot; ;  // &quot;step one&quot;   ?>   reset() function rewinds array's internal pointer to the first element and returns the value of the  first array element, or FALSE if the array is empty.
Ad

More Related Content

What's hot (20)

PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
Maulik Borsaniya
 
Java script array
Java script arrayJava script array
Java script array
chauhankapil
 
Arrays in php
Arrays in phpArrays in php
Arrays in php
Laiby Thomas
 
Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
Emertxe Information Technologies Pvt Ltd
 
Control Structures In Php 2
Control Structures In Php 2Control Structures In Php 2
Control Structures In Php 2
Digital Insights - Digital Marketing Agency
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
CPD INDIA
 
PHP slides
PHP slidesPHP slides
PHP slides
Farzad Wadia
 
JavaScript - Chapter 11 - Events
 JavaScript - Chapter 11 - Events  JavaScript - Chapter 11 - Events
JavaScript - Chapter 11 - Events
WebStackAcademy
 
Php.ppt
Php.pptPhp.ppt
Php.ppt
Nidhi mishra
 
Js ppt
Js pptJs ppt
Js ppt
Rakhi Thota
 
Event In JavaScript
Event In JavaScriptEvent In JavaScript
Event In JavaScript
ShahDhruv21
 
javascript objects
javascript objectsjavascript objects
javascript objects
Vijay Kalyan
 
Form Processing In Php
Form Processing In PhpForm Processing In Php
Form Processing In Php
Harit Kothari
 
exception handling
exception handlingexception handling
exception handling
rajshreemuthiah
 
Css selectors
Css selectorsCss selectors
Css selectors
Parth Trivedi
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
Google
 
JavaScript Control Statements I
JavaScript Control Statements IJavaScript Control Statements I
JavaScript Control Statements I
Reem Alattas
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
Varun C M
 
MYSQL - PHP Database Connectivity
MYSQL - PHP Database ConnectivityMYSQL - PHP Database Connectivity
MYSQL - PHP Database Connectivity
V.V.Vanniaperumal College for Women
 
Array in c++
Array in c++Array in c++
Array in c++
Mahesha Mano
 

Similar to Php Using Arrays (20)

Php2
Php2Php2
Php2
Keennary Pungyera
 
Introduction to Perl - Day 1
Introduction to Perl - Day 1Introduction to Perl - Day 1
Introduction to Perl - Day 1
Dave Cross
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
Dave Cross
 
Beginning Perl
Beginning PerlBeginning Perl
Beginning Perl
Dave Cross
 
Php array
Php arrayPhp array
Php array
Core Lee
 
Introduction to Perl - Day 2
Introduction to Perl - Day 2Introduction to Perl - Day 2
Introduction to Perl - Day 2
Dave Cross
 
Perl Presentation
Perl PresentationPerl Presentation
Perl Presentation
Sopan Shewale
 
CGI With Object Oriented Perl
CGI With Object Oriented PerlCGI With Object Oriented Perl
CGI With Object Oriented Perl
Bunty Ray
 
Prototype js
Prototype jsPrototype js
Prototype js
mussawir20
 
Intermediate Perl
Intermediate PerlIntermediate Perl
Intermediate Perl
Dave Cross
 
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Dhivyaa C.R
 
UNIT IV (4).pptx
UNIT IV (4).pptxUNIT IV (4).pptx
UNIT IV (4).pptx
DrDhivyaaCRAssistant
 
Modern Perl
Modern PerlModern Perl
Modern Perl
Marcos Rebelo
 
Groovy every day
Groovy every dayGroovy every day
Groovy every day
Paul Woods
 
JQuery Basics
JQuery BasicsJQuery Basics
JQuery Basics
Alin Taranu
 
Google collections api an introduction
Google collections api   an introductionGoogle collections api   an introduction
Google collections api an introduction
gosain20
 
LPW: Beginners Perl
LPW: Beginners PerlLPW: Beginners Perl
LPW: Beginners Perl
Dave Cross
 
Drupal Lightning FAPI Jumpstart
Drupal Lightning FAPI JumpstartDrupal Lightning FAPI Jumpstart
Drupal Lightning FAPI Jumpstart
guestfd47e4c7
 
Scala 2 + 2 > 4
Scala 2 + 2 > 4Scala 2 + 2 > 4
Scala 2 + 2 > 4
Emil Vladev
 
Basic PHP
Basic PHPBasic PHP
Basic PHP
Todd Barber
 
Introduction to Perl - Day 1
Introduction to Perl - Day 1Introduction to Perl - Day 1
Introduction to Perl - Day 1
Dave Cross
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
Dave Cross
 
Beginning Perl
Beginning PerlBeginning Perl
Beginning Perl
Dave Cross
 
Introduction to Perl - Day 2
Introduction to Perl - Day 2Introduction to Perl - Day 2
Introduction to Perl - Day 2
Dave Cross
 
CGI With Object Oriented Perl
CGI With Object Oriented PerlCGI With Object Oriented Perl
CGI With Object Oriented Perl
Bunty Ray
 
Intermediate Perl
Intermediate PerlIntermediate Perl
Intermediate Perl
Dave Cross
 
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Dhivyaa C.R
 
Groovy every day
Groovy every dayGroovy every day
Groovy every day
Paul Woods
 
Google collections api an introduction
Google collections api   an introductionGoogle collections api   an introduction
Google collections api an introduction
gosain20
 
LPW: Beginners Perl
LPW: Beginners PerlLPW: Beginners Perl
LPW: Beginners Perl
Dave Cross
 
Drupal Lightning FAPI Jumpstart
Drupal Lightning FAPI JumpstartDrupal Lightning FAPI Jumpstart
Drupal Lightning FAPI Jumpstart
guestfd47e4c7
 
Ad

More from mussawir20 (20)

Php Operators N Controllers
Php Operators N ControllersPhp Operators N Controllers
Php Operators N Controllers
mussawir20
 
Php Calling Operators
Php Calling OperatorsPhp Calling Operators
Php Calling Operators
mussawir20
 
Database Design Process
Database Design ProcessDatabase Design Process
Database Design Process
mussawir20
 
Php Simple Xml
Php Simple XmlPhp Simple Xml
Php Simple Xml
mussawir20
 
Php String And Regular Expressions
Php String  And Regular ExpressionsPhp String  And Regular Expressions
Php String And Regular Expressions
mussawir20
 
Php Sq Lite
Php Sq LitePhp Sq Lite
Php Sq Lite
mussawir20
 
Php Sessoins N Cookies
Php Sessoins N CookiesPhp Sessoins N Cookies
Php Sessoins N Cookies
mussawir20
 
Php Rss
Php RssPhp Rss
Php Rss
mussawir20
 
Php Reusing Code And Writing Functions
Php Reusing Code And Writing FunctionsPhp Reusing Code And Writing Functions
Php Reusing Code And Writing Functions
mussawir20
 
Php Oop
Php OopPhp Oop
Php Oop
mussawir20
 
Php My Sql
Php My SqlPhp My Sql
Php My Sql
mussawir20
 
Php File Operations
Php File OperationsPhp File Operations
Php File Operations
mussawir20
 
Php Error Handling
Php Error HandlingPhp Error Handling
Php Error Handling
mussawir20
 
Php Crash Course
Php Crash CoursePhp Crash Course
Php Crash Course
mussawir20
 
Php Basic Security
Php Basic SecurityPhp Basic Security
Php Basic Security
mussawir20
 
Javascript Oop
Javascript OopJavascript Oop
Javascript Oop
mussawir20
 
Html
HtmlHtml
Html
mussawir20
 
Javascript
JavascriptJavascript
Javascript
mussawir20
 
Object Range
Object RangeObject Range
Object Range
mussawir20
 
Prototype Utility Methods(1)
Prototype Utility Methods(1)Prototype Utility Methods(1)
Prototype Utility Methods(1)
mussawir20
 
Php Operators N Controllers
Php Operators N ControllersPhp Operators N Controllers
Php Operators N Controllers
mussawir20
 
Php Calling Operators
Php Calling OperatorsPhp Calling Operators
Php Calling Operators
mussawir20
 
Database Design Process
Database Design ProcessDatabase Design Process
Database Design Process
mussawir20
 
Php Simple Xml
Php Simple XmlPhp Simple Xml
Php Simple Xml
mussawir20
 
Php String And Regular Expressions
Php String  And Regular ExpressionsPhp String  And Regular Expressions
Php String And Regular Expressions
mussawir20
 
Php Sessoins N Cookies
Php Sessoins N CookiesPhp Sessoins N Cookies
Php Sessoins N Cookies
mussawir20
 
Php Reusing Code And Writing Functions
Php Reusing Code And Writing FunctionsPhp Reusing Code And Writing Functions
Php Reusing Code And Writing Functions
mussawir20
 
Php File Operations
Php File OperationsPhp File Operations
Php File Operations
mussawir20
 
Php Error Handling
Php Error HandlingPhp Error Handling
Php Error Handling
mussawir20
 
Php Crash Course
Php Crash CoursePhp Crash Course
Php Crash Course
mussawir20
 
Php Basic Security
Php Basic SecurityPhp Basic Security
Php Basic Security
mussawir20
 
Javascript Oop
Javascript OopJavascript Oop
Javascript Oop
mussawir20
 
Prototype Utility Methods(1)
Prototype Utility Methods(1)Prototype Utility Methods(1)
Prototype Utility Methods(1)
mussawir20
 
Ad

Recently uploaded (10)

ee case study and evaluation of biodiesel
ee case study and evaluation of biodieselee case study and evaluation of biodiesel
ee case study and evaluation of biodiesel
SwaroopDalvi
 
Violence against women , finding from the 2008 national demografic
Violence against women , finding from the 2008 national demograficViolence against women , finding from the 2008 national demografic
Violence against women , finding from the 2008 national demografic
oppateamo1234
 
crucial-conversations-training-powerpoint.pptx
crucial-conversations-training-powerpoint.pptxcrucial-conversations-training-powerpoint.pptx
crucial-conversations-training-powerpoint.pptx
vikramdas40
 
Embracing Adaptability (setback) - Istvan Patzay
Embracing Adaptability (setback) - Istvan PatzayEmbracing Adaptability (setback) - Istvan Patzay
Embracing Adaptability (setback) - Istvan Patzay
isti84
 
Miracles Through Mindset: Lessons from the Global Battle Against Polio
Miracles Through Mindset: Lessons from the Global Battle Against PolioMiracles Through Mindset: Lessons from the Global Battle Against Polio
Miracles Through Mindset: Lessons from the Global Battle Against Polio
Chandan Patary
 
How You Can Increase Your Salary by Following These Frameworks?
How You Can Increase Your Salary by Following These Frameworks?How You Can Increase Your Salary by Following These Frameworks?
How You Can Increase Your Salary by Following These Frameworks?
Chandan Patary
 
road-safety.In India, road accidents are among the top causes of death especi...
road-safety.In India, road accidents are among the top causes of death especi...road-safety.In India, road accidents are among the top causes of death especi...
road-safety.In India, road accidents are among the top causes of death especi...
ayanmalik64967
 
How to Prepare for and Survive a Power Outage
How to Prepare for and Survive a Power OutageHow to Prepare for and Survive a Power Outage
How to Prepare for and Survive a Power Outage
Bob Mayer
 
7ELeadership Framework_Mental Agility.pdf
7ELeadership Framework_Mental Agility.pdf7ELeadership Framework_Mental Agility.pdf
7ELeadership Framework_Mental Agility.pdf
Chandan Patary
 
"Master Time Management for Ultimate Productivity"
"Master Time Management for Ultimate Productivity""Master Time Management for Ultimate Productivity"
"Master Time Management for Ultimate Productivity"
srinujam1
 
ee case study and evaluation of biodiesel
ee case study and evaluation of biodieselee case study and evaluation of biodiesel
ee case study and evaluation of biodiesel
SwaroopDalvi
 
Violence against women , finding from the 2008 national demografic
Violence against women , finding from the 2008 national demograficViolence against women , finding from the 2008 national demografic
Violence against women , finding from the 2008 national demografic
oppateamo1234
 
crucial-conversations-training-powerpoint.pptx
crucial-conversations-training-powerpoint.pptxcrucial-conversations-training-powerpoint.pptx
crucial-conversations-training-powerpoint.pptx
vikramdas40
 
Embracing Adaptability (setback) - Istvan Patzay
Embracing Adaptability (setback) - Istvan PatzayEmbracing Adaptability (setback) - Istvan Patzay
Embracing Adaptability (setback) - Istvan Patzay
isti84
 
Miracles Through Mindset: Lessons from the Global Battle Against Polio
Miracles Through Mindset: Lessons from the Global Battle Against PolioMiracles Through Mindset: Lessons from the Global Battle Against Polio
Miracles Through Mindset: Lessons from the Global Battle Against Polio
Chandan Patary
 
How You Can Increase Your Salary by Following These Frameworks?
How You Can Increase Your Salary by Following These Frameworks?How You Can Increase Your Salary by Following These Frameworks?
How You Can Increase Your Salary by Following These Frameworks?
Chandan Patary
 
road-safety.In India, road accidents are among the top causes of death especi...
road-safety.In India, road accidents are among the top causes of death especi...road-safety.In India, road accidents are among the top causes of death especi...
road-safety.In India, road accidents are among the top causes of death especi...
ayanmalik64967
 
How to Prepare for and Survive a Power Outage
How to Prepare for and Survive a Power OutageHow to Prepare for and Survive a Power Outage
How to Prepare for and Survive a Power Outage
Bob Mayer
 
7ELeadership Framework_Mental Agility.pdf
7ELeadership Framework_Mental Agility.pdf7ELeadership Framework_Mental Agility.pdf
7ELeadership Framework_Mental Agility.pdf
Chandan Patary
 
"Master Time Management for Ultimate Productivity"
"Master Time Management for Ultimate Productivity""Master Time Management for Ultimate Productivity"
"Master Time Management for Ultimate Productivity"
srinujam1
 

Php Using Arrays

  • 2. Introduction Programming languages use variables to store values An array is a variable that can store a list of values Arrays can be single-dimensional or multidimensional All the values are referred by the same array name
  • 3. Defining an Array An array is a complex variable that allows you to store multiple values in a single variable (which is handy when you need to store and represent related information). An array is a variable that can store a set values of the same data type An array index is used to access an element
  • 4. Indexed Array Example <?php // define an array $pizzaToppings = array( 'onion' , 'tomato' , 'cheese' , 'anchovies' , 'ham' , 'pepperoni' ); print_r ( $pizzaToppings ); ?> //Output Array ( [0] => onion [1] => tomato [2] => cheese [3] => anchovies [4] => ham [5] => pepperoni )
  • 5. Associative Arrays An associative array is an array where the index type is string PHP also allows you to replace indices with user-defined &quot;keys&quot;, in order to create a slightly different type of array. Each key is unique, and corresponds to a single value within the array
  • 6. Associative Arrays Example <?php // define an array $fruits = array( 'red' => 'apple' , 'yellow' => 'banana' , 'purple' => 'plum' , 'green' => 'grape' ); print_r ( $fruits ); ?> //Output Array ( [red] => apple [yellow] => banana [purple] => plum [green] => grape )
  • 7. Define an Array The simplest was to define an array variable is the array() function Example; <?php // define an array $pasta = array('spaghetti', 'penne', 'macaroni'); ?> Can define an array by specifying values for each element in the index notation Example; <?php // define an array $pasta [ 0 ] = 'spaghetti' ; $pasta [ 1 ] = 'penne' ; $pasta [ 2 ] = 'macaroni' ; ?>
  • 8. Define an Array Also can define an array by using keys rather than default numeric indices Example; <?php // define an array $menu [ 'breakfast' ] = 'bacon and eggs' ; $menu [ 'lunch' ] = 'roast beef' ; $menu [ 'dinner' ] = 'lasagna' ; ?>
  • 9. Modify an Array Add an element to an array Can add elements to the array in a similar manner Also can modify the element by replace ‘anchovies ‘ with 'green olives'; Example; <?php // add an element to an array $pizzaToppings [ 3 ] = 'green olives' ; ?>
  • 10. Push And Pull Adding an element to the end of existing array with the array_push() function; Example; <?php // define an array $pasta = array( 'spaghetti' , 'penne' , 'macaroni' ); // add an element to the end array_push ( $pasta , 'tagliatelle' ); print_r ( $pasta ); ?> //Output Array ( [0] => spaghetti [1] => penne [2] => macaroni [3] => tagliatelle )
  • 11. Push And Pull Adding an element to the beginning of existing array with the array_unshift() function; Example; <?php // define an array $pasta = array( 'spaghetti' , 'penne' , 'macaroni' ); // add an element to the end array_unshift ( $pasta , 'tagliatelle' ); print_r ( $pasta ); ?> //Output Array ( [0] => tagliatelle [1] => spaghetti [2] => penne [3] => macaroni
  • 12. Push And Pull Removing an element from the end of an array using the interestingly-named array_pop() function. Example; <?php // define an array $pasta = array( 'spaghetti' , 'penne' , 'macaroni' ); // remove an element from the end array_pop ( $pasta ); print_r ( $pasta ); ?> //Output Array ( [0] => spaghetti [1] => penne )
  • 13. Push And Pull Removing an element from the top of an array using the interestingly-named array_shift() function. Example; <?php // define an array $pasta = array( 'spaghetti' , 'penne' , 'macaroni' ); // remove an element from the top array_shift ( $pasta ); print_r ( $pasta ); ?> //Output Array ( [0] => penne[1] => macaroni )
  • 14. Split a String The explode() function splits a string into smaller components, based on a user-specified delimiter, and returns the pieces as elements as an array. Example; <?php // define CSV string $str = 'red, blue, green, yellow' ; // split into individual words $colors = explode ( ', ' , $str ); print_r ( $colors ); ?> //Output Array ( [0] => red [1] => blue [2] => green [3] => yellow )
  • 15. Split a String The implode() function can creates a single string from all the elements of an array by joining them together with a user-defined delimiter. Example; <?php // define array $colors = array ( 'red' , 'blue' , 'green' , 'yellow' ); // join into single string with 'and' // returns 'red and blue and green and yellow' $str = implode ( ' and ' , $colors ); print $str ; ?> //Output red and blue and green and yellow
  • 16. Sorting sort() The sort() function arranges the element values into an alphabetical order(Ascending) Example; <?php // define an array $pasta = array( 'spaghetti' , 'penne' , 'macaroni' ); // returns the array sorted alphabetically sort ( $pasta ); print_r ( $pasta ); ?> //Output Array ( [0] => macaroni [1] => penne [2] => spaghetti )
  • 17. Sorting rsort() The rsort() function sort the element values into the descending alphabetical order Example; <?php // define an array $pasta = array( 'spaghetti' , 'penne' , 'macaroni' ); // returns the array sorted alphabetically rsort ($pasta); print_r ( $pasta ); ?> //Output Array ( [0] => spaghetti [1] => penne [2] => macaroni )
  • 18. Looping the Loop We can read an entire array by simply loop over it, using any of the loop constructs. Example; <?php // define array $artists = array( 'Metallica' , 'Evanescence' , 'Linkin Park' , 'Guns n Roses' ); // loop over it and print array elements for ( $x = 0 ; $x < sizeof ( $artists ); $x ++) {     echo '<li>' . $artists [ $x ]; } ?> //Output Metallica Evanescence Linkin Park Guns n Roses
  • 19. Looping the Loop The sizeof() function is one of the most important and commonly used array functions. It returns the size of (read: number of elements within) the array. It is mostly used in loop counters to ensure that the loop iterates as many times as there are elements in the array. By using an associative array, the array_keys() and array_values()functions come in handy, to get a list of all the keys and values within the array.
  • 20. Looping the Loop There is a simpler way of extracting all the elements of an array by using foreach() loop. A foreach() loop runs once for each element of the array passed to it as argument, moving forward through the array on each iteration. Unlike a for() loop, it doesn't need a counter or a call to sizeof(), because it keeps track of its position in the array automatically. On each run, the statements within the curly braces are executed, and the currently-selected array element is made available through a temporary loop variable. Example; <?php // define array $artists = array( 'Metallica' , 'Evanescence' , 'Linkin Park' , 'Guns n Roses' ); // loop over it // print array elements foreach ( $artists as $a ) {     echo '<li>' . $a ; } ?>
  • 21. Looping the Loop Continue //Output Metallica Evanescence Linkin Park Guns n Roses Each time the loop executes, it places the currently-selected array element in the temporary variable $a. This variable can then be used by the statements inside the loop block foreach() loop doesn't need a counter to keep track of where it is in the array Much easier to read than a standard for() loop .
  • 22. Array And Loops Arrays and loops also come in handy when processing forms in PHP For example, if want to have a group of related checkboxes or a multi-select list, just use an array to capture all the selected form values in a single variable, to simplify processing Example;
  • 23. Array And Loops <?php if (!isset( $_POST [ 'submit' ])) {      // and display form      ?>     <form action=&quot; <?php echo $_SERVER [ 'PHP_SELF' ]; ?> &quot; method=&quot;POST&quot;>     <input type=&quot;checkbox&quot; name=&quot;artist[]&quot; value=&quot;Bon Jovi&quot;>Bon Jovi     <input type=&quot;checkbox&quot; name=&quot;artist[]&quot; value=&quot;N'Sync&quot;>N'Sync     <input type=&quot;checkbox&quot; name=&quot;artist[]&quot; value=&quot;Boyzone&quot;>Boyzone     <input type=&quot;submit&quot; name=&quot;submit&quot; value=&quot;Select&quot;>     </form> <?php      } else {      // or display the selected artists     // use a foreach loop to read and display array elements      if ( is_array ( $_POST [ 'artist' ])) {         echo 'You selected: <br />' ;         foreach ( $_POST [ 'artist' ] as $a ) {            echo &quot;<i>$a</i><br />&quot; ;             }         }     else {         echo 'Nothing selected' ;     } } ?> //Output You selected: N\'Sync Boyzone
  • 25. Associative Multidimensional Array <?php $products = array( array( 'TIR', 'Tires', 100 ), array( 'OIL', 'Oil', 10 ), array( 'SPK','Spark Plugs', 4 ) ); for ( $row = 0; $row < 3; $row++ ) { for ( $column = 0; $column < 3; $column++ ) { echo '|'.$products[$row][$column]; } echo '|<br/>'; } ?>
  • 26. Array Manipulations each() function Returns the current key and value pair from the array array and advances the array cursor. This pair is returned in a four-element array, with the keys 0, 1, key, and value. Elements 0 and key contain the key name of the array element, and 1 and value contain the data. <?php $fruit = array( 'a' => 'apple' , 'b' => 'banana' , 'c' => 'cranberry' ); reset ( $fruit ); while (list( $key , $val ) = each ( $fruit )) {    echo &quot;$key => $val\n&quot; ; } ?> The above example will output: copy to clipboard a => apple b => banana c => cranberry
  • 27. <?php $array = array( 'step one' , 'step two' , 'step three' , 'step four' );   // by default, the pointer is on the first element   echo current ( $array ) . &quot;<br />\n&quot; ; // &quot;step one&quot; // skip two steps     next ( $array );                                 next ( $array ); echo current ( $array ) . &quot;<br />\n&quot; ; // &quot;step three&quot;   // reset pointer, start again on step one reset ( $array ); echo current ( $array ) . &quot;<br />\n&quot; ; // &quot;step one&quot;   ?> reset() function rewinds array's internal pointer to the first element and returns the value of the first array element, or FALSE if the array is empty.