PHP Arrays

Unlock the Power of PHP Arrays: A Comprehensive Tutorial

The purpose of arrays in PHP

The array is a type of variable used to store multiple values in PHP programs.

For example,

$arr_variable = array (1,2,3,4,5);

Mixed:

$arr_variable = array (1,2,"A","B",3);

Key/value:

$arr_variable = array(
1 => "PHP",
2 => "MySQL",
3 => "Java",
);
  • One of the advantages of arrays is that if you have to store similar types of information during the life of the program in multiple variables, you may simply create a single array variable and store all values in it.
  • Another benefit is memory allocation for an array. If you create simple variables, these will be scattered in memory. In the case of an array, the items are stored in adjacent memory locations. This is simpler to deal with in a program as compared to scattered variables.
  • For example, your PHP program gets a list of fifty names from the user in a web form. As the user presses the submit button to save or proceed to next step, you have to store those in PHP by using variables. One of the ways is to create variables for each name e.g. name1, name2, and so on.
  • The other way is to create an array of fifty elements e.g. name[].
  • In this tutorial on PHP array, I will show you working examples that include creating and accessing simple arrays and user sent data from web forms with other HTML elements, as well!

Creating arrays in PHP programs

This is how you can create arrays in PHP.

Creating an Array without keys:

$arr_variable = array (1,2,3,4,5);

A PHP array can contain both numbers and strings, e.g.:

$arr_variable = array (1,2,”A”,”B”,3);

Creating arrays with key/value pairs

$arr_variable = array(

1 => "PHP",

2 => "MySQL",

3 => "Java",

);

I will show you the role of keys in demos while accessing arrays.

You may also create arrays like this:

$arr[0] = "PHP";

$arr[1] = "MySQL";

$arr[2] = "Java";

 

PHP does not distinguish between numeric / indexed and associative arrays, so you can create arrays like this:

$arr["Course1"] = "PHP";

$arr["Course2"] = "MySQL";

$arr["Course3"] = "Java";
That means you can use a string as a key in a PHP array.

In the next section, I will show you examples with demos and code to create, access, and use different functions of PHP arrays. Some of the examples require user input to explain with HTML elements. Let me start with the basic examples.

Creating, accessing, and printing an array

  • In the following example, an array of numbers is created with five items or elements.
  • Then a foreach loop is used to access/print the array elements on the screen.
  • This is how the array is created and used with the foreach loop:
<?php

$arr_variable = array (1,2,3,4,5);



foreach( $arr_variable as $arritem )

{

echo "The array item is: $arritem <br />";

}

?>

Output:

The array item is: 1
The array item is: 2
The array item is: 3
The array item is: 4
The array item is: 5

The foreach loop is explained in its chapter.

An example of a key/value pair array

In this example, an array with key-value pair is created and then printed by using the foreach.

The following PHP code is used to create and print the array with a key/value pair:

<?php

$arr_variable = array(

1 => "PHP",

2 => "MySQL",

3 => "Java",

);

foreach( $arr_variable as $arritem )

{

echo "The array item is: $arritem <br />";

}

?>

Output:

The array item is: PHP
The array item is: MySQL
The array item is: Java

A mixed array items example with accessing a specific element

In this example, an array of numbers and strings is created. After that, instead of using a foreach loop, I will access a specific array item as follows:

$arr_variable = array (1,2,"A",4,"B");

echo "The third array item is: $arr_variable[2]";

Output:

The third array item is: A

In the code of demo page, you can see array is created with mixed item i.e. numbers and strings. After that, the third array element is displayed by using its index key.

I used [2] for the third element, which means, the index of PHP arrays starts at 0.

A simple associative array example

As such, PHP does not differentiate between simple indexed or associative arrays.

The associative arrays are those in which strings are used as keys.

See the following example:

$arr_course = array();
$arr_course["Course1"] = "PHP";
$arr_course["Course2"] = "MySQL";
$arr_course["Course3"] = "Java";


foreach($arr_course as $key_arr => $val_arr){
    echo $key_arr . " = " .$val_arr ."<br />";
}

Output:

Course1 = PHP
Course2 = MySQL
Course3 = Java

You can see, first, an array is declared which is followed by creating its elements. When creating the array elements, I used strings as keys:

$arr_course = array();

$arr_course["Course1"] = "PHP";

$arr_course["Course2"] = "MySQL";

$arr_course["Course3"] = "Java";

In the foreach loop, this time, I also accessed and displayed the array keys along with their respective items.

foreach($arr_course as $key_arr => $val_arr){

echo $key_arr . " = " .$val_arr ."<br />";

}
This is a useful feature, as such in bigger arrays this is hard to remember or access array items based on numeric indexes. Having descriptive names as keys can help describe an array for the long term as well.

I will also show its usage in an advanced demo ahead.

An example of PHP array with HTML form

In some scenarios, you may need to ask users to enter similar kinds of information, for example, enter ten names in given textboxes or some other data. You may need to store that information into the database as well.

In this example, five HTML textboxes are given to enter the names. As you click submit after filling the textboxes, those names will be displayed by using an array.

See demo online:

PHP array HTML form

Online demo and code

If you enter the names (or some dummy text) and press the submit button, you can see, the entered names are displayed.

So what is done is PHP code?

<?php

$txtnames = $_POST['txtname'];



foreach( $txtnames as $n ) {

print "The name is ".$n ."</BR>";

}

?>

First of all, an array $txtnames is assigned the form’s textbox values. In the HTML form, I used the same name for each textbox with []:

<p><label>Enter Name 1</label><input type="text" name="txtname[]" /><br /></p>

<p><label>Enter Name 2</label><input type="text" name="txtname[]" /><br /></p>

<p><label>Enter Name 3</label><input type="text" name="txtname[]" /><br /></p>

<p><label>Enter Name 4</label><input type="text" name="txtname[]" /><br /></p>

<p><label>Enter Name 5</label><input type="text" name="txtname[]" /><br /></p>
  • As this is assigned to a PHP variable, this became an array of five elements.
  • Because we have an array now, we can use the same foreach loop as used in the above examples to print array elements.
  • Practically, you may want to get records from the user in an HTML form, for any other scenarios. As they submit, you may collect the whole form’s data in PHP arrays and after establishing a connection to the database, you can insert records into the database table.
  • You may even use a form where HTML form fields are added on the fly to any number for entering data. See the following example.

An example of arrays with adding users in HTML form

In above example, only five textboxes were given where you may enter the names. In certain scenarios, it is up to the users to add as many records as they want. For example, adding users, products, orders, etc.

  • This example is a combination of HTML form, jQuery’s method, and PHP arrays.
  • As the demo page loads, only two textboxes are shown to enter “New user name” and “New user Email”.
  • Above that, a button is given, “Add More Users”.
  • By clicking that, you can add as many textboxes as you want. After adding more textboxes to create users, fill the textboxes with some dummy data.
  • After that, press the Submit button where PHP arrays will be used to collect that information. This information will be taken and displayed back to the HTML page.

See demo online:

PHP array dynamic

Online demo and code

Following are the steps to do this task:

Step 1:

Creating the HTML markup and CSS to show textbox fields along with a submit button. It also includes a button to add textboxes for more users.

<h1>A PHP array demo</h1>

<button id="appendex">Add More Users</button>

<form action="" method="post">

<div class="divcls">

<p class="para"><label>New User Name</label>: <input name="username[]" title="Enter User name"/></br>

<label>New User Email</label>: <input name="useremail[]" title="Enter Email address"/></p>

</div>

<input type="submit" value="Submit and Display Users"/>

</form>

Step 2:

The jQuery code where, I used the $.append method to add textbox fields for user name and email.

<script>

$(document).ready(function(){

$("#appendex").click(function(){

$(".divcls").append("<p class='para'><label>New User Name</label>: <input name='username[]' title='Enter User name'/>     <label>New User Email</label>: <input name='useremail[]' title='Enter Email address'/></p>");

});



});

</script>

If you notice, the names of the textboxes are the same in markup and jQuery part:

For user name: username[]

For email: useremail[]

This will help in using these as arrays in the PHP code.

Step 3:

The CSS for the table, paragraph, and div elements. The table’s CSS class is used in the PHP section for displaying entered users’ data.

See the <style> section on the demo page.

Step 4:

This is where you need to focus, i.e. where I used the PHP arrays:

<?php

$usernames = $_POST['username'];

$txtemails = $_POST['useremail'];



echo "<table class='table_bg'><tr><th>User Name</th><th>User Email</th></tr>";

foreach( $usernames as $key => $uname ) {

//echo "<p class='para'>The User name is:".$uname." and User email is: ".$txtemails[$key]."</p>";

echo ("<tr><td>$uname</td><td>$txtemails[$key]</td></tr>");

}

echo ("</table>");

?>

First of all, user names and emails are collected, that can be any number; 1, 2, 3 even 1000+. These are assigned to PHP variables that are arrays.

In the next line, echo statement is used to create an HTML table with table headings. The table tag is assigned the CSS class that I created in the head section.

After that, a foreach loop is used to go through the arrays. The array elements (user names and emails) are printed in the HTML table.

Note that, this is again just for the demo purpose to make you understand how PHP arrays can be mixed up with web page elements.

In other scenarios, you may need to store user’s data (or some other information) in the database’s table. So rather using an HTML table in the foreach, you can write the script to insert data in a database.

An example of two-dimensional array

Creating an array inside an existing array is referred to as the multi-dimensional array.

Alternatively, you can say that when an array acts as the value of an array it becomes a multi-dimensional array.

  • If you go through the two levels, it will be a two-dimensional array. For three levels, it will be called three-dimensional arrays.
  • In all the above examples, the arrays were one dimensional. Because we simply used the key/value pairs.
  • If key = another array, this will be two-dimensional.
  • See the following example of creating and using the two-dimensional array.

Code:

$arrusers = array();
$arrusers[0]['user_name'] = 'User 1';
$arrusers[0]['user_email'] = 'user1@example.com';

$arrusers[1]['user_name'] = 'User 2';
$arrusers[1]['user_email'] = 'user2@example.com';

$arrusers[2]['user_name'] = 'User 3';
$arrusers[2]['user_email'] = 'user3@example.com';

foreach ($arrusers as $row) {
    echo $row['user_name'] . "</BR>";
    echo $row['user_email']. "</BR>";

}

Output:

User 1
user1@example.com
User 2
user2@example.com
User 3
user3@example.com

So this is how a two-dimensional array is created:

$arrusers = array();

$arrusers[0]['user_name'] = 'User 1';

$arrusers[0]['user_email'] = 'user1@example.com';

You may also create this as follows:

$ arrusers[0] = array();

$arrusers[0]['user_name'] = 'User 1';

$arrusers[0]['user_email'] = 'user1@example.com';

$ arrusers[1] = array();

$arrusers[1]['user_name'] = 'User 2';

$arrusers[1]['user_email'] = 'user2@example.com';

This is also equivalent to the above example of creating two-dimensional arrays:

$arrusers = array(

0 => array(

'user_name' => 'User 1',

'user_email' => 'user1@example.com'

),

1 => array(

'user_name' => 'User 2',

'user_email' => 'user2@example.com'

),

2 => array(

'user_name' => 'User 3',

'user_email' => 'user3@example.com'

)

);

In the demo, the foreach loop is used to access the array elements.

A few useful array method examples

Now let me show you a few examples of using useful array functions. There are plenty of array PHP functions. You can see the list here.

The array count function example

The count function is used to return the total elements in an array. See the following example to use PHP count function with an array:

After creating an array of five elements, a for loop is used. In the for loop, the count function is used to return the length of the array:

<?php

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


for ($i=0; $i <count($arr_variable); $i++){

echo    "The array item is: $arr_variable[$i] <br />";

}

?>

Output:

The array item is: 10
The array item is: 20
The array item is: 30
The array item is: 40
The array item is: 50

The loop will keep on executing until all elements of the array are displayed.

A PHP array sort example

The array sort function is used to arrange the array elements from lowest to highest or alphabetically.

See a demo online where an array of string elements is created:

<?php

$arr_course = array ("PHP","Java","Python","CSS","HTML");

echo "Array before sorting! <br /><br />";

for ($i=0; $i<count($arr_course); $i++){

echo    "The array item is: $arr_course[$i] <br />";

}

echo "<br /><br />Array after sorting! <br /><br />";

sort($arr_course);

for ($i=0; $i<count($arr_course); $i++){

echo    "The array item is: $arr_course[$i] <br />";

}

?>

In the demo, you can see the array before and after using the sort method. Initially, array was created randomly:

$arr_course = array ("PHP","Java","Python","CSS","HTML");

Before and after using the sort method, the output is:

Array before sorting!

The array item is: PHP

The array item is: Java

The array item is: Python

The array item is: CSS

The array item is: HTML

Array after sorting!

The array item is: CSS

The array item is: HTML

The array item is: Java

The array item is: PHP

The array item is: Python

You can see, the array is arranged alphabetically after using the PHP sort array method.

Author - Atiq Zia

Atiq is the writer at jquery-az.com, an online tutorial website started in 2014. With a passion for coding and solutions, I navigate through various languages and frameworks. Follow along as we unravel the mysteries of coding together!