Php – Array Variable Type
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.
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
We can also define an array just initializing or giving values like below.
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 = "Ahmet";
$students = "Ali";
$students = "İsmail";
$students = "Elif";
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
by default. This means default array with 4 element index numbers starts from
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
$students = "Jack";
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.
And we can access associative arrays by specifying string. We will get
ismail age from associative array.
$age = $students["ismail"];
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.
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.