Friday, 30 August 2019

Arrays in PHP



PHP Arrays
PHP array is an ordered map (contains value on the basis of key). It is used to hold multiple values of similar type in a single variable.

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.

PHP Array Types
There are 3 types of array in PHP.
1.Indexed Array
2.Associative Array


PHP Indexed Array
PHP index is represented by number which starts from 0. We can store number, string and object in the PHP array. All PHP array elements are assigned to an index number by default.
There are two ways to define indexed array:
<?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

PHP Associative Array
We can associate name with each array elements in PHP using => symbol.
<?php   
$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");   
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>"; 
echo "John salary: ".$salary["John"]."<br/>"; 
echo "Kartik salary: ".$salary["Kartik"]."<br/>"; 
?>   
Output:
Sonoo salary: 350000
John salary: 450000
Kartik salary: 200000

Identifying Elements of an array

in_array() function

The in_array( ) function is an inbuilt function of PHP. It is used to search an array for a specific value. If the third parameter strict is set to true, the in_array( ) function will also check the types of the $values.
Returns
The function returns true if the value is found in the array or false otherwise.
<?php 
$record = array(15, 24, 30, 100); 
if (in_array("100", $record)) 
{ 
echo "found"; 
} 
else 
{ 
echo "not found"; 
} 
?> 
Output:found

key() function

The key( ) function returns the element key from the current internal pointer position. This function was introduced in 4.0.
Returns
The key( ) returns the key of the array element that is currently being pointed by the internal pointer.

Example 1
<?php 
$subject=array("java","php","ruby","python"); 
echo "The key from the current position is: " . key($subject); 
?> 
Output:The key from the current position is: 0

Example 2
<?php 
$subjects = array(Subject1 => "OS", Subject2 => "compiler", Subject3 => "dbms"); 
echo "Current position Key is : " . key($subjects); 
?> 
Output:Current position Key is : Subject1

array_keys() function

The array_keys() function is used to get all the keys or a subset of the keys of an array. It returns the keys, numeric and string, from the input array. This function was introduced in PHP 4.0.

EXAMPLE 1
<?php 
$array1=array("virat" => 100, "sachin" => 200, "ganguly" => 300, "rahul" => 400); 
print_r(array_keys($array1)); 
?> 
Output:Array ( [0] => virat [1] => sachin [2] => ganguly [3] => rahul )

EXAMPLE 2
<?php 
$a=array("a"=>"javatpoint","b"=>"php","c"=>"java"); 
print_r(array_keys($a)); 
?> 
Output:
Array ( [0] => a [1] => b [2] => c )

array_key_exists() function

The array_key_exists( ) is an builtin function of PHP. The array_key_exists( ) function checks an array for a specified key, and returns true if the key exists and false if the key does not exists. This function was introduced in PHP 4.0.7.
Return Type
The array_key_exists( ) function returns true if the key exists and false if the key does not exist.

EXAMPLE 1
<?php 
$a=array("a"=>"apple","b"=>"ball"); 
if (array_key_exists("c",$a)) 
    { 
        echo "Key exists!"; 
    } 
else 
    { 
        echo "Key does not exist!"; 
    } 
?> 
Output:Key does not exist!

isset() Function

The isset() function is an inbuilt function in PHP which checks whether a variable is set and is not NULL. This function also checks if a declared variable, array or array key has null value, if it does, isset() returns false, it returns true in all other possible cases.
<?php
 
// isset() function
$num = '0';
 
if( isset( $num ) )
{
 print_r(" $num is set with isset function <br>");
}
     
?>
Output:0 is set with isset function

Function reset()

The 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.
<?php
$input = array('foot', 'bike', 'car', 'plane');
$mode = end($input);
print "$mode <br />";
  
$mode = reset($input);
print "$mode <br />";
  
$mode = current($input);
print "$mode <br />";
?>
This will produce following result −
plane
foot
foot

unset() Function

The unset() function is an inbuilt function in PHP which is used to unset a specified variable.
The behavior of this function depends on different things. If the function is called from inside of any user defined function then it unsets the value associated with the variables inside it, leaving the value which is initialized outside it.
It means that this function unsets only local variable. If we want to unset the global variable inside the function then we have to use $GLOBALS array to do so.
<?php
 
$var = "hello";
     
 // No change would be reflected outside
function unset_value()
{
unset($var);
}
    
unset_value();
echo $var;
?>
Outside:hello


Converting between Arrays and variables.

extract() function

The extract( ) function is an inbuilt function of PHP, and it is used to import variables into the local symbol table from an array. This function was introduced in 4.0.
<?php 
$characters = array('hero'=>'batman','villain'=>'joker'); 
extract($characters); 
echo $hero; 
echo $villain 
?> 
Output:batmanjoker

compact() function
The compact( ) function is an inbuilt function of PHP, and it is used to create an array from variables and their values. This function was introduced in PHP 4+.
Return Values
This function returns an array with all the variables added to it.
<?php 
$firstname = "sachin"; 
$lastname = "tendulkar"; 
$age = 45; 
$result = compact("firstname", "lastname", "age"); 
print_r($result); 
?> 
Output:
Array
(
    [firstname] =>sachin
    [lastname] =>tendulkar
    [age] => 45
)

explode() Function
PHP explode() is string function, which is used to split a string by a string. In another words we can say that the It break a string into an array. The "separator" parameter cannot be an empty string.
Syntax:
explode(separator,string,limit); 

<?php 
$str = "Hello Google. It's a Browser."; 
print_r (explode(" ",$str)); 
?> 
Output:
Array ( [0] => Hello [1] => Google. [2] => It's [3] => a [4] => Browser. )

Implode() Function
PHP string implode() is predefined function that is used to join array elements with a string.
<?php 
$arr = array('Hello','PHP','Javatpoint'); 
echo "After using 'implode()' function: ".implode(" ",$arr);; 
?> 
Output:After using 'implode()' function: Hello PHP Javatpoint

Sorting:-

sort() function
The PHP sort( ) function is used to sort the array elements in ascending order. This function was introduced in PHP 4.0.
<?php 
$cars = array("bmw", "audi", "nissan"); 
sort($cars); 
print_r($cars); 
?> 
Output:

Array
(
[0] =>audi
[1] =>bmw
[2] =>nissan
)

asort() function
The asort( ) function is an inbuilt function of PHP. The asort( ) function is used to sort an associative array in ascending order, according to the value. This function was introduced in PHP 4.0.
Return:-It returns true on success or false on failure.

<?php 
$color = ['G'=>'Black','Y'=>'Green','C'=>'Yellow','B'=>'White','W'=>'Cyan']; 
asort($color); 
print_r($color); 
?> 

Output:
Array
(
    [G] => Black
    [W] => Cyan
    [Y] => Green
    [B] => White
    [C] => Yellow
)

arsort( ) function

The array_arsort( ) function is an inbuilt function of PHP. The array_arsort( ) function is used to sort an array in reverse order and the function maintains index association. This function was introduced in 4.0.
Return Values:-The array_arsort( ) function returns true on success and false on failure.

<?php 
$city = array("Bengaluru","noida","hyderabad"); 
arsort($city); 
print_r($city); 
?> 
Output:
Array
(
  [1] =>noida
  [2] =>hyderabad
  [0] => Bengaluru
)

rsort() function

The PHP rsort( ) function is used to sort an array in reverse order. This function introduced in PHP 4.0.
Returns:-The PHP rsort( ) function returns true on success or false on failure.

<?php 
$fruit = array("d"=>"mango", "a"=>"orange", "b"=>"banana" ); 
rsort($fruit); 
print_r($fruit); 
?> 
Output:
Array
(
    [0] => orange
    [1] => mango
    [2] => banana
)

ksort() function
The PHP ksort() sorts an associative array in ascending order, according to the key. It is mainly used for an associative array. This function was introduced in PHP 4.0.
Returns:-The ksort() function returns true on success and false on failure.

<?php
$age=array("sachin"=>"45","virat"=>"29","ganguly"=>"46"); 
ksort($age); 
print_r($age); 
?> 
Output:
Array
(
    [ganguly] => 46
    [sachin] => 45
    [virat] => 29
)

krsort() function
The PHP krsort( ) function is used to sort the array elements by the key in descending order. It is mainly used in the associative array. This function was introduced in PHP 4.0.

Returns:-The krsort( ) function returns true on success or false on failure.
<?php 
$lang = array("x" => "html", "y" => "java", "z" => "php");  
krsort($lang); 
print_r($lang); 
?> 
Output:
Array
(
    [z] =>php
    [y] => java
    [x] => html
)

Action on Entire Arrays

 

is_array — Finds whether a variable is an array

 

Return Values

Returns TRUE if var is an array, FALSE otherwise.

<?php

$yes = array('this', 'is', 'an array');

echo is_array($yes) ? 'Array' : 'not an Array';

echo "\n";

$no = 'this is a string';

echo is_array($no) ? 'Array' : 'not an Array';

?>

The above example will output:

Array

not an Array

 

shuffle() function

 

The PHP shuffle( ) function is used to randomize the order of the elements in the array. The function assigns new keys to the elements in an array. This function introduced in PHP 4.0.

 

Returns

The shuffle( ) function returns true on success or false on failure.

<?php 

$city = array(1 => "hyderabad", 2 => "bangalore", 3 => "kolkata"); 

shuffle($city); 

print_r($city); 

?> 

Output- Every time output is random

(

    [0] =>bangalore

    [1] =>hyderabad

    [2] =>kolkata

)

 

Adding and Removing Array Elements

 

array_push() Function

 

The array_push() function inserts one or more elements to the end of an array.

Note: Even if your array has string keys, your added elements will always have numeric keys

 

<html>

<body>

<?php

$a=array("a"=>"red","b"=>"green");

array_push($a,"blue","yellow");

print_r($a);

?>

</body>

</html>

 

Array ( [a] => red [b] => green [0] => blue [1] => yellow )

 

array_pop() Function

The array_pop() function deletes the last element of an array.

<html>

<body>

<?php

$a=array("red","green","blue");

array_pop($a);

print_r($a);

?>

</body>

</html>

 

Array ( [0] => red [1] => green )

 

array_shift() Function

The array_shift() function removes the first element from an array, and returns the value of the removed element.

Note: If the keys are numeric, all elements will get new keys, starting from 0 and increases by 1

<html>

<body>

<?php

$a=array(0=>"red",1=>"green",2=>"blue");

echo array_shift($a)."<br>";

print_r ($a);

?>

</body>

</html>

 

red

Array ( [0] => green [1] => blue )

 

array_unshift() Function

The array_unshift() function inserts new elements to an array. The new array values will be inserted in the beginning of the array.

Note: Numeric keys will start at 0 and increase by 1. String keys will remain the same.

 

<html>

<body>

<?php

$a=array(0=>"red",1=>"green");

array_unshift($a,"blue");

print_r($a);

?>

</body>

</html>

Array ( [0] => blue [1] => red [2] => green )

 

array_splice() Function

The array_splice() function removes selected elements from an array and replaces it with new elements. The function also returns an array with the removed elements.

 

<html>

<body>

<?php

$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");

$a2=array("a"=>"purple","b"=>"orange");

array_splice($a1,0,2,$a2);

print_r($a1);

?>

</body>

</html>

 

Array ( [0] => purple [1] => orange [c] => blue [d] => yellow )

 

Determining Array size and Uniqueness

 

array_count() function

The count( ) function is an inbuilt function of PHP, and it is used to count the elements of an array or the properties of an object. This function was introduced in PHP 4.0.

Return

The count( ) function returns the number of elements in an array.

<?php 

$fruits=array("Banana","Cherry","Apple"); 

echo count($fruits); 

?> 

 

Output:3

 

 array_count_values() function

The array_count_values() function returns an array where the keys are the original array's values, and the values is the number of occurrences. In other words, we can say that array_count_values() function is used to calculate the frequency of all of the elements of an array.

 

Return Type

Returns an associative array, where the keys are the original array's values, and the values are the number of occurrences. This function is introduced in PHP 4

 

<?php 

$details = array(3, "Hii", 3, "World", "Hii"); 

print_r(array_count_values($details)); 

?> 

Output:

Array( [3] => 2  [Hii] => 2  [World] => 1 )

 

array_unique( ) function

The array_unique( ) function is an inbuilt function of PHP and it is used to remove duplicate values from an array. This function was introduced in 4.0.1

Return

The array_unique( ) function returns the filtered array.

<?php 

$news = array("a"=>"zee", "b"=>"zee", "c"=>"aajtak", "d"=>"ndtv"); 

print_r(array_unique($news)); 

?> 

Output:

Array

(

    [a] => zee

    [c] =>aajtak

    [d] =>ndtv

)


list() Function

The list() function is used to assign values to a list of variables in one operation.

Note: This function only works on numerical arrays.

<html>

<body>

<?php

$my_array = array("Dog","Cat","Horse");

list($a, $b, $c) = $my_array;

echo "I have several animals, a $a, a $b and a $c.";

?>

</body>

</html>

 

I have several animals, a Dog, a Cat and a Horse.

 

range() Function

The range() function creates an array containing a range of elements.

This function returns an array of elements from low to high.

Note: If the low parameter is higher than the high parameter, the range array will be from high to low.

<html>

<body>

<?php

$number = range(0,5);

print_r ($number);

?>

</body>

</html>

 

Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 4 [5] => 5 )

 

array_merge() function

The array_merge( ) function is a built-in function of PHP. This function is used to merge the elements or values of two or more arrays together into a single array. This function was introduced in PHP 4.0.

 

Return Type

The array_merge( ) function returns the merged array.

<?php 

$game1=array("a"=>"cricket","b"=>"hockey"); 

$game2=array("c"=>"football","b"=>"tennis"); 

print_r(array_merge($game1,$game2)); 

?> 

Output:Array ( [a] => cricket [b] => tennis [c] => football )

 

array_intersect() function

The array_intersect( ) function is used to Computes the intersection of arrays. It compares two or more arrays and returns an array containing all the values of the first array that are present in other arrays. In this operation, keys are preserved. This function was introduced in PHP 4.0.1.

Return Type

It returns an array containing the entries from array1 that are present in all of the other arrays.

<?php 

$lang1 = array("a" => "java", "python", "ruby"); 

$lang2 = array("b" => "java", "javascript", "python"); 

$result = array_intersect($lang1, $lang2); 

print_r($result); 

?> 

Output:Array ( [a] => java [0] => python )

 

array_diff() function

The array_diff() function compares two or more arrays and returns an array with the keys and values from the first array, only if the value is not present in any of the other arrays. This function was introduced in PHP 4.0.

Return Type:-It returns an array containing the entries from array1 that are not present in any of the other arrays.

<?php 

$x1=array(0=>"netbeans",1=>"eclipse",2=>"bluej"); 

$x2=array(3=>"bluej",4=>"eclipse",5=>"intellij"); 

$result=array_diff($x1,$x2); 

print_r($result); 

?> 

Output:

Array (   [0] => netbeans )

 

array_diff_assoc() function

The array_diff_assoc() function is used to compare an array against another array and returns the difference. In other words, we can say that array_diff_assoc() function compares the keys and values of two or more arrays and return an array that contains the entries from array1 that are not present in array2 or array3. This function was introduced in PHP 4.3.

 

Return Type:-Returns an array containing all the values from array1 that are not present in any of the other arrays.

<?php 

$a1=array("1"=>"red","2"=>"green","3"=>"blue","4"=>"black"); 

$a2=array("1"=>"red","2"=>"blue","3"=>"green"); 

$result=array_diff_assoc($a1,$a2); 

print_r($result); 

?> 

Output:-Array ( [2] => green [3] => blue  [4] => black  )

 

array_sum() function

The array_sum( ) function is an inbuilt function of PHP. The array_sum( ) function calculates the sum of values in an array and returns the sum of values in an array as an integer or float. This function was introduced in PHP 4.0.4.

Return:-The array_sum( ) function returns the sum of values.

<?php 

$sum = array(13, 26, 39, 52); 

print_r(array_sum($sum)); 

?> 

Output:130

 

array_reverse() function

The array_reverse() function is a inbuilt function of PHP. The array_reverse( ) function is used to reverse the order of the elements in an array. This function was introduced in PHP 4.0.

Return type

The array_reverse() function returns the reversed array.

<?php 

$lang = array("a"=>"PHP","b"=>"JAVA","c"=>"PYTHON"); 

print_r(array_reverse($lang)); 

?> 

Output:-Array ( [c] => PYTHON [b] => JAVA [a] => PHP )

 

array_pad() Function

The array_pad() function inserts a specified number of elements, with a specified value, to an array.

<html>

<body>

<?php

$a=array("red","green");

print_r(array_pad($a,5,"blue"));

?>

 

</body>

</html>

Array ( [0] => red [1] => green [2] => blue [3] => blue [4] => blue )

 

array_slice() Function

The array_slice() function returns selected parts of an array.

<html>

<body>

<?php

$a=array("red","green","blue","yellow","brown");

print_r(array_slice($a,2));

?>

</body>

</html>

Array ( [0] => blue [1] => yellow [2] => brown )

 

array_chunk() Function

The array_chunk() function splits an array into chunks of new arrays.

<html>

<body>

<?php

$cars=array("Volvo","BMW","Toyota","Honda","Mercedes","Opel");

print_r(array_chunk($cars,2));

?>

</body>

</html>

 

Array ( [0] => Array ( [0] => Volvo [1] => BMW ) [1] => Array ( [0] => Toyota [1] => Honda ) [2] => Array ( [0] => Mercedes [1] => Opel ) )

 

array_filter() function

The array_filter( ) function filters the values of an array using a callback function. This function passes each value of the input array to the callback function.

<?php 

$arr1=array(1,2,6,5,10,3); 

function fun($num) 

return $num%2==0;  

 } 

print_r(array_filter($arr1,'fun')); 

?> 

Output:-Array ( [1] => 2 [2] => 6 [4] => 10 )

 

Manual Traversing

 

current() function

The current( ) function is an inbuilt function of PHP, and it is used to return the value of the current element in an array. This function was introduced in PHP 4.0.

 

Return Values

The current( ) function returns the value of the current element in an array or false on empty elements.

<?php 

$array = array("javatpoint", "udemy", "udacity", "coursera", "edureka"); 

print_r(current($array));

?> 

Output:-javatpoint

 end() function

The end( ) function is an inbuilt function of PHP. The end() function Set the internal pointer of an array to its last element. This function was introduced in 4.0.

Returns:-The end( ) function returns the value of the last element in the array on success or false if the array is empty.

 <?php 

$crickter = array("sachin", "ganguly", "virat", "sehwag"); 

echo end($crickter);  

?> 

Output:-sehwag

 

next() function

The PHP next( ) function is used to advance the internal array pointer. It advances the internal array pointer one place forward before returning the element value. This function was introduced in PHP 4.0.

Returns

The PHP next( ) function returns the value of the next element in the array on success or false if there are no more elements.

<?php 

$company = array("java", "T", "point","coding", "every language"); 

echo next($company); 

?> 

Output:-T

 

reset() function

The PHP reset( ) function is used to move the array's internal pointer to the first element. This function was introduced in PHP 4.0.

Returns

The reset( ) function returns the value of the first array element or false if the array is empty.

Example 1

<?php 

$arr = array('sachin', 'sehwag', 'ganguly', 'rahul'); 

$result = reset($arr); 

print "$result"; 

?> 

Output:-sachin

 Traversing index based array  while(),for(),foreach()

 While Loop

PHP while loop can be used to traverse set of code like for loop.

It should be used if number of iteration is not known.

While Loop Example

<?php 

$n=1; 

while($n<=10){ 

echo "$n<br/>"; 

$n++; 

?> 

Output:

1

2

3

4

5

6

7

8

9

10

 For Loop

PHP for loop can be used to traverse set of code for the specified number of times.

It should be used if number of iteration is known otherwise use while loop

<?php 

for($n=1;$n<=10;$n++){ 

echo "$n<br/>"; 

?> 

Output:

1

2

3

4

5

6

7

8

9

10

 

For Each Loop

PHP for each loop is used to traverse array elements.

<?php 

$season=array("summer","winter","spring","autumn"); 

foreach( $season as $arr ){ 

  echo "Season is: $arr<br />"; 

?> 

Output:

Season is: summer

Season is: winter

Season is: spring

Season is: autumn

 

Multidimensional Arrays

The dimension of an array indicates the number of indices you need to select an element.

•For a two-dimensional array you need two indices to select an element

•For a three-dimensional array you need three indices to select an element

 

PHP - Two-dimensional Arrays

A two-dimensional array is an array of arrays (a three-dimensional array is an array of arrays of arrays).

<?php

  // PHP program to create  // multidimensional array

  // Creating multidimensional // array

$myarray = array(

    

    // Default key for each will

    // start from 0

    array("Ankit", "Ram", "Shyam"),

    array("Unnao", "Trichy", "Kanpur")

);

    

// Display the array information

print_r($myarray);

?>

 Output:

Array

(

    [0] => Array

        (

            [0] => Ankit

            [1] => Ram

            [2] => Shyam

        )

     [1] => Array

        (

            [0] => Unnao

            [1] => Trichy

            [2] => Kanpur

        )

 )

 

Three Dimensional Array: It is the form of multidimensional array. Initialization in Three-Dimensional array is same as that of Two-dimensional arrays. The difference is as the number of dimension increases so the number of nested braces will also increase.

<?php

 // PHP program to creating three

// dimensional array

 // Create three nested array

$myarray = array(

    array(

        array(1, 2),

        array(3, 4),

    ),

    array(

        array(5, 6),

        array(7, 8),

    ),

);

     

// Display the array information

print_r($myarray);

?>

Output:

Array

(

    [0] => Array

        (

            [0] => Array

                (

                    [0] => 1

                    [1] => 2

                )

             [1] => Array

                (

                    [0] => 3

                    [1] => 4

                )

         )

     [1] => Array

(            [0] => Array

                (

                    [0] => 5

                    [1] => 6

                )

             [1] => Array

                (

                    [0] => 7

                    [1] => 8

                )

        )

 )