Arrays in php

3. Arrays in PHP

In PHP, arrays are ordered data maps and are used to store, manage and operate a set of variables. To put it simply, an array is a data structure that holds multiple data within a single identifier. There are two parts in an Array – Values and Keys. While Values  ontain information to be stored, Keys are used to identify these values. It is allocated to a single variable. It holds significant information, popularly termed as Array Elements. This information can be used for a number of times in a program. Either non negative Integers or Strings are used as Keys. The arrays that use non-negative Integers as Keys are termed as Scalar Arrays. These are Associative Arrays that use Strings as keys. An Array may contain different Array(s) popularly known as Multidimensional Arrays. The syntax of an Array is as follows: $array[key] = value; Look at the simple example below: Example:
<?php
$student_array[0] = “Rohit”;

$student_array[1] = “Rahul”;

$student_array[2] = “Sourav”;

$student_array[3] = “Abdul”;
?>
In the above example, the names of the students (Rohit, Rahul, Sourav and Abdul) are the Values and the numeric characters (0, 1, 2 and 3) are the Keys of this array. Scalar array: The numeric values are used as ‘Keys’ in Scalar Array. To put it simply, we can use integers as index numbers in scalar arrays. In case of scalar arrays, keys start from zero (0). Look at the examples below: Example 1:
<?php

$colors = array(“red”,”brown”,”yellow”);

print_r($colors);

?>
The output of this program is as follows: Array ( [0] => red [1] => brown [2] => yellow )   Here, multiple values are simultaneously assigned to an array. It is also possible to assign values to an array one by one using keys as shown below: Example 2:
<?php

$numerals = array( );

$numerals[]=”3”;

$numerals[]=”9”;

$numerals[]=”11”;

$numerals[]=”7”;
?>
  Associative array: Associative arrays are indexed with strings in lieu of numbers. Look at the example below: Example:
<?php

$marks[“Ram”] = 80;

$marks[“Raj”] = 60;

$marks[“Rahul”] = 50;

$marks[“Rajam”] = 0;

echo “Ram Obtained- “ . $marks[“Ram”] . “<br />”;

echo “Raj Obtained- “ . $marks[“Raj”] . “<br />”;

echo “Rahul Obtained- “ . $marks[“Rahul”] . “<br />”;

echo “Rajam Obtained- “ . $marks[“Rajam”];

?>
The output of this program is as follows: Ram Obtained- 80 Raj Obtained- 60 Rahul Obtained- 50 Rajam Obtained- 0   asort( ) – This function is used to sort an associative array on values. arsort( ) – This function is used to sort an associative array on values in reverse order.   3.1 Creating arrays The array() language constructor is used to create an array in PHP. Look at the syntax below: array( [key =>] value , … ) // The key may be either an integer or a string //The value is any reusable value Let’s see how we can create an array by using the array() function:
<?php
$countries = array (“INDIA”, “PAKISTAN”, “JAPAN”);
?>
Here we can access the second element by using the index “1”. Let’s see:
<?php
echo “$country[1]”;
?>
The output of this program is: “PAKISTAN”. Now let’s see how we can create an array by using an array identifier:
<?php
$countries[] = “INDIA”;

$countries[] = “PAKISTAN”;

$countries[] = “JAPAN”;
?>
Here, the values are inserted in the same order as the earlier one. Using the index number, we can place the data as per our requirement. You can insert these index numbers inside the square brackets. Look at the following code:
<?php
$countries[1] = “PAKISTAN”;

$countries[2] = “JAPAN”;

$countries[0] = “INDIA”;
?>
Example 1:
<?php

$learn = array(foo => “I am learning how to create an array”, 12 => true);

echo $learn[foo]; // I am learning how to create an array

echo”<br>”;

echo $learn[12]; // Unit 01

?>
The output of this program is as follows: I am learning how to create an array 1 While creating an array, first we denote a variable name as an array:
<?php

$learning = array( );

?>
Next, specify the array that will hold the specified value. Use a comma to separate the listed values of an array. Look at the PHP code below:
<?php

$learning = array(

“Basic”,

“Intermediate”,

“Advanced”

);

?>
Example 2:
<?php

// Learning to create array.

$array_learning = array(10, 20, 30, 40, 50);

print_r($array_learning);

//Let’s delete every item and we leave the array itself intact:

foreach ($array_learning as $i => $value) {

unset($array_learning[$i]);

}

print_r($array_learning);

// Append an item (note that the new key is 50,instead of 0).

$array_learning[] = 60;

print_r($array_learning);

// Re-index:

$array_learning = array_values($array_learning);

$array_learning[] = 70;

print_r($array_learning);

?>
The output of this program is as follows: Array ( [0] => 10 [1] => 20 [2] => 30 [3] => 40 [4] => 50 ) Array ( ) Array( [5] => 60 ) Array ( [0] => 60 [1] => 70 )   3.2 Multidimensional arrays Multidimensional Arrays are the most complex arrays in PHP. As the name suggests, these are data structures that hold various other arrays. Various arrays are used as sub-array elements in a Multidimensional Array. We can easily identify the difference between a single dimensional array and a multidimensional array.In a single dimensional array, we set a value for a single key and assign a number of values to several keys. For example, we may assign values like ‘class’, ‘section’, ‘roll number’ to a single dimensional array that contains information on ‘Student’. On the other hand, a multidimensional array ‘Student’ may include the break up like, ‘Personal data’ ‘Marks’, ‘Attendance,’ etc. Each of these sections is a single dimensional array that is treated as a separate array. Look at the example below: Example 1: Here we have created a ‘Multidimensional Array’ by using the automatically assigned ID keys:
$relatives = array

(

“Robin”=>array

(

“Ram”,

“Bharat”,

“Adam”

),

“Raj”=>array

(

“Gili”

),

“Brate”=>array

(

“Sita”,

“Lorel”,

“Charles”

)

);

Example 2:

<?php

$vegetables = array (

“vegetables” => array (

“a” => “potato”,

“b” => “banana”,

“c” => “spinach”

),

“numbers” => array (

1,

2,

3,

4,

5,

6

),

“holes” => array (

“first”,

5 => “second”,

“third”

)

);

// These are some examples to address values in the array that is mentioned above

echo $vegetables[“holes”][5]; // prints “second”

echo $vegetables[“vegetables”][“a”]; // prints “potato”

unset($vegetables[“holes”][0]); // remove “first”

// This is developing a new multi-dimensional array

$juices[“spinach”][“green”] = “good”;

?>
  3.3 Navigating arrays Here we need to know the number of elements while accessing these.
  • sizeof($arr): In PHP, the sizeof($aar) function returns the number of elements in the array. This can also be used to initialise a loop counter while processing the array.
Example:
<?php

$data = array(“yellow”, “green”, “red”);

echo “This Array includes “ . sizeof($data) . “elements”;

?>
The output of this program is as follows: This Array includes 3 elements.   There is another function count() that also returns the number of elements of an array. To access the elements of a scalar array, you can use the ‘for’ statement.For example, the elements of the array in the above example can be displayed by using the ‘for’ statement. Look at the code below:
for($a=0;$a<3;$a++)

echo “<br>”.$data[$a];
The elements of an associative array cannot be accessed using the ‘for’ statement. In this case, we can use the ‘foreach’ statement. The elements of a scalar array are also accessible through this statement. The following example can also be written by using the ‘foreach’ statement. See the code below: foreach($data as $a) echo $a; Now let us see how to access the elements of an associative array by using the ‘foreach’ statement. We can use the ‘foreach’ statement in the following way: foreach($array_name as $key=>$val) Example:
<?php

$asso_array=array(Roll=>1,

Name=>”Tom”,

Grade=>”B”);

foreach($asso_array as $abc=>$xyz)

echo $abc.”=”.$xyz.”<br>”;

?>
The output of this program is: Roll=1 Name=Tom Grade=B   The each($arr) function is used to repetitively navigate to an array. When the each() function is called, it returns the current key as well as the value of the array. Here, the array cursor is also moved forward by one element. This function is popularly used in a loop. Example:
<?php

$data = array(“Protagonist” => “Jack”, “Jam” => “Harry”);

while (list($key, $value) = each($data)) {

echo “$key: $value \n”;

}

?>
The output of this program is: Protagonist: Jack Jam: Harry The techniques described above can be used to access the elements of multidimensional array.   3.4 Manipulating Keys Keys play an important role in an array, especially in an associative array. There are some functions that can manipulate the keys of an array. Some of these functions are given below:
  • array_keys($arr): The array_keys($arr) function is used to recover the keys  from an associative array. This function receives a PHP array and a new array is returned. This new array contains only the keys of the array. The complementary part of this function is the array_values() function.
Example:
<?php

$data = array(“Protagonist” => “Jack”, “Milliate” => “Jill”);

print_r(array_keys($data));

?>
The output of this program is as follows: Array ([0] => Protagonist,[1] => Milliate )   3.5 Manipulating arrays Now let’s see how various functions are used in PHP to manipulate arrays:
  • array_values($arr) : array_values($arr) function receives a PHP array. It returns a new array that contains only the values of the array and excludes the keys. The array_keys() function is used as the complementary part of the array_values($arr) function. You can use the array_values($arr) function to recover values from an associative array.
Example:
<?php

$data = array(“Protagonist” => “Jack”, “Milliate” => “Jill”);

print_r(array_values($data));

?>
The output of this program is as follows: Array ( [0] => Jack,[1] => Jill)  
  •  array_pop($arr) : The array_pop($arr) function removes an element from the end of an array and returns its value.
Example:
<?php

$data = array(“Jack”, “Milliate”, “Mack”);

array_pop($data);

print_r($data);

?>
The output of this program is as follows: Array([0] => Jack,[1] => Milliate)  
  • array_push($arr, $val): The array_push($aar,$val) function inserts an element at the end of an array.
Example:
<?php

$data = array(“Jack”, “Jill”, “Dick”);

array_push($data, “Harry”);

print_r($data);

?>
The output of this program is as follows: Array ( [0] => Jack, [1] => Jill, [2] => Dick,[3] => Harry)  
  • array_shift($arr) : The array_shift($aar) function is used to remove an element from the beginning of an array.
Example:
<?php

$data = array(“Jack”, “Jam”, “Dick”);

array_shift($data);

print_r($data);

?>
The output of this program is as follows: Array([0] => Jam,[1] => Dick)  
  • array_unshift($arr, $val): The array_unshift($aar,$val) function adds an element to the beginning of an array.
Example:
<?php

$data = array(“Jack”, “Jill”, “Dick”);

array_unshift($data, “Sana”);

print_r($data);

?>
The output of this program is: Array ([0] => Sana,[1] => Jack,[2] => Jill,[3] => Dick)  
  • sort($arr) : The sort($aar) function sorts the elements in an array in a ascending order. In the following example, the values of the elementsin an array of characters are arranged in ascending alphabetical order.
Example:
<?php

$data = array(“b”, “d”, “a”, “c”);

sort($data);

print_r($data);

?>
The output of this program is as follows: Array ( [0] => a,[1] => b,[2] => c,[3] => d)   There are some other functions that are used to sort data in a particular order. These are rsort(), asort(), arsort(), ksort(), rsort(). rsort() – Sorts scalar array in reverse order. asort() – Sorts associative array by values. arsort() – Sorts associative array by values in reverse order. ksort( ) – Sorts associative array by ‘Keys’. krsort( ) – Sorts associative array by ‘Keys’ in reverse order.  
  • array_flip($arr) : The array_flip($arr) function interchanges the keys and the values of an Associative array.
Example:
<?php

$data = array(“x” => “Mangoes”, “y” => “Potatoes”);

print_r(array_flip($data));

?>
The output of this program is as follows: Array ( [Mangoes] => x [Potatoes] => y )  
  • array_reverse($arr) : The array_reverse($arr) function reverses the order of the elements in an array.
Example:
<?php

$data = array(11, 21, 26, 61);

print_r(array_reverse($data));

?>
The output of this program is: Array ( [0] => 61 [1] => 26 [2] => 21 [3] => 11 )  
  • array_merge($arr) : The array_merge($aar) function merges two or more  arrays. This helps to create a merged array. This function is also used to combine multiple data into a single structure.
Example:
<?php

$data1 = array(“ram”, “shyam”);

$data2 = array(“jack”, “jam”);

print_r(array_merge($data1, $data2));

?>
The output of this program is: Array ( [0] => ram,[1] => shyam,[2] => jack,[3] => jam )  
  • array_rand($arr) :The array_rand($arr) function selects one or more
than one random elements from an array. Example:
<?php

$data = array(“yellow”, “pink”, “green”);

echo “Display the color “ . $data[array_rand($data)];

?>
The output of this program is: Display the color green  
  • array_slice($arr, $offset, $length) :The array_slice($aar,$offset,$length) function is useful to extract the elements of an array. It extracts the elements from array offset $offset. This extracting is continued until the array slice $length element is elongated.
Example:
<?php

$data = array(“pink”, “yellow”, “green”, “red”);

print_r(array_slice($data, 1, 2));

?>
The output of this program is: Array ( [0] => yellow, [1] => green )  
  • array_unique($data) : The array_unique($data) function is used to remove all duplicate entries in the array.
Example:
<?php

$data = array(15,15,19,21,33,19);

print_r(array_unique($data));

?>
The output of this program is: Array  ( [0] => 15,  [3] => 21, [19] => 33, [5] => 19)  
  • array_walk($arr, $func) :The array_walk($aar, $func) function is used while performing custom processing on the various sections of an array. This function returns an altered array.
Example:
<?php

function reduce(&$a, $b) {

$a -= $a * 0.1;

}

$ourarray = array(10,20,30,40);

array_walk($ourarray, ‘reduce’);

print_r($ourarray);

?>
The output of this program is: Array ( [0] => 9 [1] => 18 [2] => 27 [3] => 36 )   3.6 Serializing arrays The serialize() function is used to generate a representation of values that the array holds. This means that it is used to serialise some PHP values. It stores the PHP values without loosing its type and structure. These serialised values can be un-serialised by using the unserialize() function. The serialize() function can not serialise the variables of type ‘Resource’. Example 1:
<?php

// $session_data contains a multi-dimensional array with session

// information for the current user. We use serialize() to store

// it in a database at the end of the request.

$con = odbc_connect(“webdb”, “php”, “bird”);

$a=odbc_prepare($con,“UPDATE sessions SET data = ? WHERE id=?”);

$sqldata = array (serialize($session_data),

$_SERVER[‘PHP_AUTH_USER’]);

if (!odbc_execute($a, &$sqldata)) {

$a=odbc_prepare($con,“INSERT INTO sessions(id, data) VALUES(?, ?)”);

if (!odbc_execute($a, &$sqldata)) {

/* Something went wrong.. */

}

}

?>
Example:
<?php

if($_POST[submit]) {

$ourarray = array(); // New, blank array.

foreach($_POST as $key => $a) {

if($key!=”submit”) { // We want to exclude the submit button

$ourarray[$key] = $a;

}

}

$ourarray = serialize($ourarray); // Serializes our new array.

$b = fopen(“owndata.txt”,”r+”);

$write = fwrite($b,$newarray);

if($write) { // If it works, which it will...

echo “It worked!”;

}

else { // In the unlikely event of the plane crashing...

}

}

?>

<?php

?>

<input type=”submit” id=”submit” name=”submit”

value=”Update” />

</form>
The output of this program is as follows: Bottom of Form Example (unserialize() function):
<?php

// Here, we use unserialize() to load session data to the

// $session_data array from the string selected from a database.

// This example complements the one described with serialize().

$con = odbc_connect(“webdb”, “php”, “bird”);

$a=odbc_prepare($conn, “SELECT data FROM sessions WHERE id =?”);

$sqldata = array($_SERVER[‘PHP_AUTH_USER’]);

if (!odbc_execute($a, &$sqldata) || !odbc_fetch_into($a, &$tmp)) {

//if the execute or fetch fails, initialize to empty array

$session_data = array();

} else { // we should now have the serialized data in $tmp[0].

$session_data = unserialize($tmp[0]);

if (!is_array($session_data)) {

// something went wrong, initialize to empty array

$session_data = array();

}

}

?>