What are PHP Arrays

What is an Array?

A PHP array is an entity which stores multiple values in one single variable. An array is actually an ordered map, which is a type that associates values with keys.

It is one type of variable or it’s better to say that it is a collection of variables from different types. They have one general name and each variable has its own key and value. The array key can only be expressed in a’string’ or an ‘integer’ method and the first key can start with negative numbers. The value can be from every type.

If you want to create an array with the ‘array ()’ function, you must type the array general name with a ‘$’ sign first, then the ‘=’ sign and after that, the ‘array ()’ function will come. The structure of using the ‘array ()’ function as you see in the following example is that you type the key, then ‘=>’ and after that the value of each key comes. A ‘Notice’ error may appear because of undefined keys, but it doesn’t lead to a malfunction. Be careful when you want to use an array. Its keys must come between brackets to access their values.

If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this.

$cars1 = "Volvo";
$cars2 = "BMW";
$cars3 = "Toyota"; 

An array can hold many values under a single name, and you can access the values by referring to an index number.

Create an Array in PHP

In PHP, the array() function is used to create an array.

array();

If you want to create an array with the ‘array ()’ function, you must type the array general name with a ‘$’ sign first, then the ‘=’ sign and after that, the ‘array ()’ function will come. The structure of using the ‘array ()’ function as you see in the following example is that you type the key, then ‘=>’ and after that the value of each key comes. A ‘Notice’ error may appear because of undefined keys, but it doesn’t lead to a malfunction. Be careful when you want to use an array. Its keys must come between brackets to access their values.

<?php
$teacher= array( 1=> "Mike" , 2=> "Jim");

Echo $teacher[2];  // Prints Jim
?>

Another way that you can create an array is using brackets after an array name for each key, and putting a value after ‘=’ sign. Look at the example of this kind:

<?php
$StudentFName['Sara'] = 'Peter';

$StudentMark['Tom']= 18;

$StudentMark['Bob']= 19;

$StudentMark['Leo']= 17.5;

Echo $StudentMark ['Bob'];  // Prints 19

Echo $StudentFName ['Sara'];  // Prints Peter
?>

What happens if you forget the quotes for string keys’ values (‘string’ values)? If the key used doesn’t conflict with anything else, it works! Don’t worry about it, but a notice will be shown!

How can we get rid of the notices? It may be off on your web server, and it’s the local server on your computer that lets it be on, to provide you with better programming; But, to turn it off, you can use ‘error_reporting (Null)’. So you don’t have unimportant errors anymore.

PHP, has three types of arrays:

  1. Indexed array ->Array with a numeric index
  2. Associative array->Array with named keys
  3. Multidimensional array->Array containing one or more arrays

PHP Indexed Array:

An indexed array is like an ordered list of items. For example let’s say you have a grocery list:

<?php
$groceries[0] = "olives\n";
  $groceries[1] = "lettuce\n";
  $groceries[2] = "salad dressing";
 
  $arraylength = count($groceries);
  for ($i = 0; $i < $arraylength; $i++) {
    echo $groceries[$i];
  }

One of the main reasons for creating an array is so you can easily loop through the data. Here we introduce the “for” loop. This loop echoes each of the values in the grocery array. We would not be able to do this if we had independent variables such as $groceries0, $groceries1, and $groceries2.

The variable $i in our loop is a counter that changes depending on which element in the array we want to echo. $i is initially assigned a value of 0. What is contained in the curly brackets of the for loop is executed as long as $i is less than $arraylength (which is simply the size of the array, in this case, the value of 3). The command $i++ says what to do after the curly brackets are executed. In this case, $i++ means $i = $i+1 or that we just add 1 to the value so we can print the next element of the array.

Another way of creating an indexed array is as follows:

<?php
  $groceries = array("olives\n", "lettuce\n", "salad dressing");
 
  $arraylength = count($groceries);
  for ($i = 0; $i < $arraylength; $i++) {
    echo $groceries[$i];
  } ?>

That’s it. We’ve covered a lot of ground so feel free to ask questions in the comments. We’ll cover other types of arrays next.

PHP Associative Array:

In 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 indexes as keys and assign values to them.

Associative arrays are very similar to numeric arrays in terms of functionality, but they are different in terms of their index. Associative arrays will have their index as a string so that you can establish a strong association between key and values.

NOTE Don’t keep the associative array inside the double quote while printing, otherwise it would not return any value.

Example:

<?php
/* First method to associate create array. */
$salaries = array("sara" => 3000, "william" => 2000, "peter" => 500);

echo "Salary of sara is ". $salaries['sara'] . "
";
echo "Salary of william is ".  $salaries['william']. "
";
echo "Salary of peter is ".  $salaries['peter']. "
";

/* Second method to create array. */
$salaries['sara'] = "high";
$salaries['william'] = "medium";
$salaries['peter'] = "low";

echo "Salary of sara is ". $salaries['niks'] . "
";
echo "Salary of william is ".  $salaries['william']. "
";
echo "Salary of peter is ".  $salaries['peter']. "
";
?>

Output

Salary of sara is 3000
Salary of william is 2000
Salary of peter is 500
Salary of sara is high
Salary of william is medium
Salary of peter is low

PHP Multidimensional Array:

In a multi-dimensional 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. Values in the multi-dimensional array are accessed using multiple indexes.

Example:

<?php
$marks = array(
"Sara" => array (
"physics" => 35,
"maths" => 30,
"chemistry" => 39
),

"william" => array (
"physics" => 30,
"maths" => 32,
"chemistry" => 29
),

"peter" => array (
"physics" => 31,
"maths" => 22,
"chemistry" => 39
)
);

/* Accessing multi-dimensional array values */
echo "Marks for sara in physics : " ;
echo $marks['sara']['physics'] . "
";

echo "Marks for william in maths : ";
echo $marks['william']['maths'] . "
";

echo "Marks for peter in chemistry : " ;
echo $marks['peter']['chemistry'] . "
";
?>

Output:

Marks for sara in physics : 35
Marks for william in maths : 32
Marks for rahul in chemistry : 39

PHP Array Functions

We have many array functions. Now we are introducing more important new ones.

You can test whether a name is an array or not, by using the ‘is_array ($name)’ function. It returns ‘true’ or ‘false’ as an answer.

How many items are existed in an array? The ‘count($array)’ or its alias ‘sizeof($array)’ function returns the number. Echo it to print the count of the array indexes:

<?php
$a[2]= 'salam'; $a[67]=67; $a['o']= true;
Echo count($a)  //prints 3
?>

To arrange the values of an array ascending, the’sort ($array)’ is used. It removes existing keys and reindexes all values starting from zero. To sort in descending mode, use’sort ($array)’. Be careful in sorting values of different types (an array with an ‘integer’ value and a’string’ one, for example). It may lead to errors. The sorting functions are used for all types. Here are some examples:

<?php
$t= array(2=>3 , 's'=>-4, 5=>5, 8=>4);
sort($t);
print_r($t);
echo '
';
rsort($t);
print_r($t);
?>

Output:

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

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

But how the indexes can be saved? Maybe they are important IDs! To do it use ‘asort($array)’ and ‘arsort($array)’ instead. So compare below outputs with above ones for finding differences in keys:

<?php
$t= array(2=>3 , 's'=>-4, 5=>5, 8=>4);
asort($t);
print_r($t);
echo '
';
arsort($t);
print_r($t);
?>

It is possible to sort arrays based on the keys of them. The functions are ‘ksort($array)’ and ‘krsort($array)’. The usage is obvious.

Another useful function is ‘array_search(Value,$array)’. It returns the key adjusted for the given value if it is existed, otherwise the returned value is false or empty ‘string’:

<?php
$t= array(2=>3 ,'s'=>-4, 5=>5, 8=>'o');
$b= array_search(-4, $t);
echo $b;    // Prints 3
echo array_search('o', $t);  // Prints 8
echo array_search(9, $t);  // Prints Nothing!
?>

We can have the summation of an array values by ‘array_sum($array)’ function:

<?php
$mark= array(2=>3 ,'s'=>-4, 5=>54);
echo array_sum($mark);  // Prints 53
?>

PHP Sorting Arrays

sort array in php

The elements in an array can be sorted in alphabetical or numerical order, descending or ascending for example sort(),rsort() ,asort() ,ksort() ,arsort(),krsort()

PHP – Sort Functions For Arrays:

we will go through the following PHP array sort functions

  1. sort() – sort arrays in ascending order
  2. rsort() – sort arrays in descending order
  3. asort() – sort associative arrays in ascending order, according to the value
  4. ksort() – sort associative arrays in ascending order, according to the key
  5. arsort() – sort associative arrays in descending order, according to the value
  6. krsort() – sort associative arrays in descending order, according to the key

Sort Array in Ascending Order – sort() :

we use sort() like below example:

<?php 
$fruts = array(banana,apple,mango); 
sort($fruts); 
?> 

Out Put

apple
banana
mango

Sort Array in Descending Order – rsort()

The following example sorts the elements of the $fruts array in descending alphabetical order

Example

<?php
$fruts =array(banana,apple,mango);
rsort($fruts);
?>

Out Put:

mango
banana
apple

The following example sorts the elements of the $numbers array in descending numerical order

Example

<?php 
$numbers = array(5, 7, 3, 23, 12); 
rsort($numbers); 
?>

Out Put:

23
12
7
5
3

Sort Array  (Ascending Order And According to Value) – asort()

The following example asort():

Example:

<?php 
$age = array("alex"=>"36", "jon"=>"38", "Joe"=>"43");
asort($age);
?> 

Out Put:

Key=alex, Value=36
Key=jon, Value=38
Key=Joe, Value=43

Sort Array (Ascending Order), According to Key – ksort()

Example:

<?php
$age = array("nik"=>"35", "sara"=>"37", "alex"=>"43");
ksort($age);
?>
Key=sara, Value=37
Key=alex, Value=43
Key=nik, Value=35

Sort Array (Descending Order), According to Value – arsort()

Example:

<?php
$age = array("nik"=>"35", "raj"=>"37", "alex"=>"43");
arsort($age);
?>
Key=alex, Value=43
Key=raj, Value=37
Key=nik, Value=35

Sort Array (Descending Order), According to Key – krsort()

Example

<?php
$age = array("nik"=>"35", "raj"=>"37", "alex"=>"43");
krsort($age);
?>
Key=nik, Value=35
Key=alex, Value=43
Key=raj, Value=37

Add a Comment

Your email address will not be published. Required fields are marked *

ABOUT CODINGACE

My name is Nohman Habib and I am a web developer with over 10 years of experience, programming in Joomla, Wordpress, WHMCS, vTiger and Hybrid Apps. My plan to start codingace.com is to share my experience and expertise with others. Here my basic area of focus is to post tutorials primarily on Joomla development, HTML5, CSS3 and PHP.

Nohman Habib

CEO: codingace.com

Request a Quote









PHP Code Snippets Powered By : XYZScripts.com