[rps-include post=6522]
We have used single value variable types up to now. But the real world problems may need different solutions and variables then those. We generally define,use multiple and a lot of values. Defining one by one variable is not a practical solution for these situations.
For example we want to store 5 students names in a single variable. We call these as arrays. Arrays can hold multiple values.
Define Array
Arrays can be defined in different ways. One of them is just providing the type as array. This will not put any data into array. In this example we will create a array named $students
.
$students=array();
We can also define an array just initializing or giving values like below.
Initialize Array
We programmers generally use most faster way of defining and initializing an array. We will simply provide the array elements in square brackets by separating them with command. In this example we will define array named $students
and put students names elements.
$students = array("Ahmet" , "Ali", "İsmail" , "Elif" );
This type of array definition and initialization is same as like below.
$students = array(); $students[0] = "Ahmet"; $students[1] = "Ali"; $students[2] = "İsmail"; $students[3] = "Elif";
Index Numbers
As you see we are using numbers to specify array index. Index is used to specifically specify an element in array. Index numbers starts from 0
by default. This means default array with 4 element index numbers starts from 0
and up to 3
. We can access array elements by giving index number. Index numbers are specified in square brackets.
In the following example we will change the element which index numbers is 1
.
$students[1] = "Jack";
Associative Arrays
We have used index numbers to specify specific elements in previous part. Array have another usage for specifying elements in array. It is called associative
. We can set strings to specify index numbers like names. In this example we will use students names as array element specifier.
$students=array("ismail"=>33,"ali"=>5,"elif"=>9);
And we can access associative arrays by specifying string. We will get ismail
age from associative array.
$age = $students["ismail"];
Multidimensional Arrays
We have use single dimension arrays up to now. We can also use array inside array. These type of arrays called multidimensional arrays. There is no restriction about the level of dimensions. In the following example we will define an array which holds student information arrays inside it.
$students=array( array("ismail",12), array("ali",5) , array("elif",9) );
We can access the inner arrays elements and values by using square brackets.
echo $students[0][0]; echo $students[0][1];
Print Arrays
Printing whole array is one of the most used function and debug operation while developing applications. We can print whole array with the print_r()
function by providing the array. We will print array named $student
in the following example.
print_r($students);

[rps-include post=6522]