PHP Tutorials: Array

In every programming language there is a variable type called array. Array has already been explain in our previous tutorial PHP: Data Type. Array allow us to store one or more type of value or values in you PHP program. Array save our time and efforts to declare multiple variables when it comes to big programs. Let us take an example. We can store name of cars in following 2 ways.

<?php
	// Method 1
	$car_name_1 = 'Audi';
	$car_name_2 = 'BMW';
	$car_name_3 = 'Toyota';

	// Method 2
	$car_name = array( 'Audi', 'BMW', 'Toyota' );

?>

In the first method I used individual variable name to store the value wherein the another method I used an array to store the value. Store value in an array and accessing it is very simple. Let us extent the above example.

<?php
	$car_name = array( 'Audi', 'BMW', 'Toyota' );
	echo $car_name[0]; // OUTPUT: Audi
	echo $car_name[1]; // OUTPUT: BMW
	echo $car_name[2]; // OUTPUT: Toyota
?>

You can see in the example we accessed the values with it’s array index. Index is a key or a number where the value get stored.

Array numeric index always starts from 0 and not from 1.

Types of Arrays

There are 3 types of array in PHP

  1. Indexed array
  2. Associative array
  3. Multidimensional array
Indexed Array

An array which store the value with numeric key index is called Indexed array. It’s is one of the most common arrays in PHP. The example above is an indexed array. The index always starts from 0 and not from 1. To access the first element of the array you have use 0.

<?php
	$car_name = array( 'Audi', 'BMW', 'Toyota' );
	echo $car_name[0]; // OUTPUT: Audi
	echo $car_name[1]; // OUTPUT: BMW
	echo $car_name[2]; // OUTPUT: Toyota
?>
Associative Array

When a user defines the index or key for a array value it’s called an associative array. The key can be numeric, alphabetic or alphanumeric.

<?php
	$students = array(
		'John Doe' => 'MCA',
		'Mark Zu' => 'BCA',
		'Ramon' => 'PhD'
	);
	echo $students['John Doe']; // OUTPUT: MCA
	echo $students['Mark Zu']; // OUTPUT: BCA
	echo $students['Ramon']; // OUTPUT: PhD
?>
Multidimensional Array

An array with sub array inside is called a multidimensional array. In this array instead on values only you can store another array. It is very easy to declare, you don’t need any special data type or anything else.

<?php
	
	$students = array(
		array(
			'name' = 'John Doe',
			'class' => 'MCA'
		),
		array(
			'name' = 'Mark Zu',
			'class' => 'BCA'
		),
		array(
			'name' = 'Ramon',
			'class' => 'PhD'
		),
	);
	
	echo 'Studend name: '.$students[0]['name'].' is in class'. $students[0]['class'];
	//OUTPUT: Studend name: John Doe is in class MCA
?>

Try out some example and share you comments here.

One thought on “PHP Tutorials: Array

Leave a Reply

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