Saturday, March 28, 2020

PHP Array

An array is a data structure that stores one or more similar type of values in a single value. The arrays are helpful to create a list of elements of similar types, which can be accessed using their index or key. 
Let's suppose you want to store colors in your PHP script. Storing the colors one by one in a variable could look something like this:
<?php  
 $color1 = "Red";  
 $color2 = "Green";  
 $color3 = "Blue";  
 ?> 
But what, if you want to store the states or city names of a country in variables and this time this not just three may be hundred. It is quite hard, boring, and bad idea to store each city name in a separate variable. And here array comes into play.

Advantage of PHP Array

  • Less Code: We don't need to define multiple variables.
  • Easy to traverse: By the help of single loop, we can traverse all the elements of an array.
  • Sorting: We can sort the elements of array.
     There are basically three types of arrays in PHP:
  • Indexed or Numeric Arrays: An array with a numeric index where values are stored linearly.
  • Associative Arrays: An array with a string index where instead of linear storage, each value can be assigned a specific key.
  • Multidimensional Arrays: An array which contains single or multiple array within it and can be accessed via multiple indices.

Indexed or Numeric Arrays
These types of arrays can be used to store any type of elements, but an index is always a number. By default, the index starts at zero. These arrays can be created in two different ways as shown in the following example:
<?php
 
// One way to create an indexed array
$name_one = array("Manish", "Sachin", "Ram", "Salim", "Raghav");
 
// Accessing the elements directly
echo "Accessing the 1st array elements directly:\n";
echo $name_one[2], "\n";
echo $name_one[0], "\n";
echo $name_one[4], "\n";
 
/* Second method to create array. */
$numbers[0] = "one";
$numbers[1] = "two";
$numbers[2] = "three";
$numbers[3] = "four";
$numbers[4] = "five";
        
// Looping through an array to access array elements using foreach
echo "Looping using foreach: \n";
 foreach( $numbers as $value ) {
echo "Value is $value <br />";
    }

// Looping through an array to access array elements using for
echo "\nLooping using for: \n";
for($i=0;$i<5;$i++)
echo $ numbers [$i]," ";


Associative Arrays
The associative arrays are very similar to numeric arrays in term of functionality but they are different in terms of their index. Associative array will have their index as string so that you can establish a strong association between key and values.
To store the salaries of employees in an array, a numerically indexed array would not be the best choice. Instead, we could use the employee's names as the keys in our associative array, and the value would be their respective salary.
NOTE − Don't keep associative array inside double quote while printing otherwise it would not return any value.

<?php
/* First method to associate create array. */
$salaries = array("Manish" => 2000, "Ramesh" => 1000, "zara" => 500);
       
echo "Salary of Manish is ". $salaries[Manish] . "<br />";
echo "Salary of Ramesh is ".  $salaries[Ramesh]. "<br />";
echo "Salary of zara is ".  $salaries['zara']. "<br />";
        
/* Second method to create array. */
$salaries[Manish] = "high";
$salaries[Ramesh] = "medium";
$salaries['zara'] = "low";

// Looping through an array using foreach       
echo "Looping using foreach: \n";
foreach ($salaries as $key => $val){
    echo "Salary of ".$key." is ".$val."\n";
}
?>

// Looping through an array using for
echo "\nLooping using for: \n";
$keys = array_keys($salaries);
$round = count($salaries); 
for($i=0; $i < $round; ++$i) {
    echo $keys[$i] . ' ' . $salaries [$keys[$i]] . "\n";
}


Multidimensional Arrays
Multi-dimensional arrays are such arrays that store another array at each index instead of a single element. In other words, we can define multi-dimensional arrays as an array of arrays. As the name suggests, every element in this array can be an array and they can also hold other sub-arrays within. Arrays or sub-arrays in multidimensional arrays can be accessed using multiple dimensions.
Example-1:
$emp = array  
  (  
  array(1,"sonoo",400000),  
  array(2,"john",500000),  
  array(3,"rahul",300000)  
  );  
  
for ($row = 0; $row < 3; $row++) {  
  for ($col = 0; $col < 3; $col++) {  
    echo $emp[$row][$col]."  ";  
  }  
echo "<br/>";  


Example-2:
<?php
         $marks = array(
            "Manish" => array (
               "physics" => 35,
               "maths" => 30,
               "chemistry" => 39
            ),
           
            "Ramesh" => array (
               "physics" => 30,
               "maths" => 32,
               "chemistry" => 29
            ),
           
            "zara" => array (
               "physics" => 31,
               "maths" => 22,
               "chemistry" => 39
            )
         );
        
         /* Accessing multi-dimensional array values */
         echo "Marks for Manish in physics : " ;
         echo $marks['Manish']['physics'] . "<br />";
        
         echo "Marks for Ramesh in maths : ";
         echo $marks['Ramesh']['maths'] . "<br />";
        
         echo "Marks for zara in chemistry : " ;
         echo $marks['zara']['chemistry'] . "<br />";
      ?>


PHP Array Functions

PHP provides various array functions to access and manipulate the elements of array. The important PHP array functions are given below.

1.     PHP array() function: PHP array() function creates and returns an array. It allows you to create indexed, associative and multidimensional arrays.

Example
<?php    
$season=array("summer","winter","spring","autumn");    
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";    
?>    
Output:
Season are: summer, winter, spring and autumn

2.     PHP array_chunk() function: PHP array_chunk() function splits array into chunks. By using array_chunk() method, you can divide array into many parts.

Example
<?php    
$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");    
print_r(array_chunk($salary,2));   
?>    
Output:
Array ( 
[0] => Array ( [0] => 550000 [1] => 250000 ) 
[1] => Array ( [0] => 200000 )
)

3.     PHP count() function: PHP count() function counts all elements in an array.

Example
<?php    
$season=array("summer","winter","spring","autumn");    
echo count($season);    
?>    
Output:
4

4.     PHP sort() function: PHP sort() function sorts all the elements in an array.

Example
<?php    
$season=array("summer","winter","spring","autumn");    
sort($season);  
foreach$season as $s )    
{    
  echo "$s<br />";    
}    
?>    
Output:
autumn
spring
summer
winter

5.     PHP array_reverse() function: PHP array_reverse() function returns an array containing elements in reversed order.

Example
<?php    
$season=array("summer","winter","spring","autumn");    
$reverseseason=array_reverse($season);  
foreach$reverseseason as $s )    
{    
  echo "$s<br />";    
}    
?>    
Output:
autumn
spring
winter
summer

6.      PHP array_search() function: PHP array_search() function searches the specified value in an array. It returns key if search is successful.

Example
<?php    
$season=array("summer","winter","spring","autumn");    
$key=array_search("spring",$season);  
echo $key;    
?>    
Output:
2

7.     PHP array_intersect() function: PHP array_intersect() function returns the intersection of two array. In other words, it returns the matching elements of two array.

Example
<?php    
$name1=array("sonoo","john","vivek","smith");    
$name2=array("umesh","sonoo","kartik","smith");    
$name3=array_intersect($name1,$name2);  
foreach$name3 as $n )    
{    
  echo "$n<br />";    
}    
?>    
Output:
sonoo
smith

8.     Viewing Array Structure function: and Values: You can see the structure and values of an array by using one of two statements var_dump() or print_r(). The print_r() statement, however, it gives somewhat less information. Consider the following example:

Example
<?php
$cities = array("London", "Paris", "New York"); 
// Display the cities array
print_r($cities);
?>
Output:
Array ( [0] => London [1] => Paris [2] => New York )
This output shows the key and the value for each element in the array. To get more information, use the following statement:
Example
<?php
// Define array
$cities = array("London", "Paris", "New York"); 
// Display the cities array
var_dump($cities);
?>
Output:
array(3){[0]=>string(6) "London" [1]=>string(5) "Paris" [2]=>string(8) "NewYork"}

This output shows the data type of each element, such as a string of 6 characters, in addition to the key and value. 

PHP Array Sorting
PHP comes with a number of built-in functions designed specifically for sorting array elements in different ways like alphabetically or numerically in ascending or descending order. Here we'll explore some of these functions most commonly used for sorting arrays.
  • sort() and rsort() — For sorting indexed arrays
  • asort() and arsort() — For sorting associative arrays by value
  • ksort() and krsort() — For sorting associative arrays by key

Sorting Indexed Arrays in Ascending Order

The sort() function is used for sorting the elements of the indexed array in ascending order (alphabetically for letters and numerically for numbers).
Example:
<?php    
  // Define array    
  $colors = array("Red", "Green", "Blue", "Yellow");    
  // Sorting and printing array    
  sort($colors);    
  print_r($colors);   
  $numbers = array(1, 2, 2.5, 4, 7, 10);    
  sort($numbers);    
  print_r($numbers);   
 ?> 
 Output:
Array ( [0] => Blue [1] => Green [2] => Red [3] =>Yellow )
Array ( [0] => 1 [1] => 2 [2] => 2.5 [3] => 4 [4] => 7 [5] => 10 )

Sorting Indexed Arrays in Descending Order
The rsort() function is used for sorting the elements of the indexed array in descending order (alphabetically for letters and numerically for numbers).
Example:
<?php   
  $colors = array("Red", "Green", "Blue", "Yellow");   
  rsort($colors);   
  print_r($colors);   
  $numbers = array(1, 2, 2.5, 4, 7, 10);   
  rsort($numbers);   
  print_r($numbers);   
?>  
Output:
Array ( [0] => Yellow [1] => Red [2] => Green [3] => Blue )
Output:
Array ( [0] => 10 [1] => 7 [2] => 4 [3] => 2.5 [4]=> 2 [5] => 1 )

Sorting Associative Arrays in Ascending Order By Value
The asort() function sorts the elements of an associative array in ascending order according to the value. It works just like sort(), but it preserves the association between keys and its values while sorting.

Example
<?php   
  $age = array("Peter"=>20, "Harry"=>14, "John"=>45, "Clark"=>35);   
  // Sorting array by value and print   
  asort($age);   
  print_r($age);   
?> 
Output:
Array ( [Harry] => 14 [Peter] => 20 [Clark] => 35 [John] => 45 )

Sorting Associative Arrays in Descending Order By Value
The arsort() function sorts the elements of an associative array in descending order according to the value. It works just like rsort(), but it preserves the association between keys and its values while sorting.
Example
<?php
// Define array
$age = array("Peter"=>20, "Harry"=>14, "John"=>45, "Clark"=>35);
// Sorting array by value and print
arsort($age);
print_r($age);
?>
Output:
Array ( [John] => 45 [Clark] => 35 [Peter] => 20 [Harry] => 14 )

Sorting Associative Arrays in Ascending Order By Key

The ksort() function sorts the elements of an associative array in ascending order by their keys. It preserves the association between keys and its values while sorting, same as asort() function.
Example
<?php
// Define array
$age = array("Peter"=>20, "Harry"=>14, "John"=>45, "Clark"=>35);
// Sorting array by key and print
ksort($age);
print_r($age);
?>
Output:
Array ( [Clark] => 35 [Harry] => 14 [John] => 45 [Peter] => 20 ) 

Sorting Associative Arrays in Descending Order By Key

The krsort() function sorts the elements of an associative array in descending order by their keys. It preserves the association between keys and its values while sorting, same as arsort() function.
Example
<?php
// Define array
$age = array("Peter"=>20, "Harry"=>14, "John"=>45, "Clark"=>35);
// Sorting array by key and print
krsort($age);
print_r($age);
?>
Output:
Array ( [Peter] => 20 [John] => 45 [Harry] => 14 [Clark] => 35 )