Arrays in PHP

In this tutorial we will learn about Arrays in PHP. In simple words an Array is variable which makes us able to store more than one same kind values using a single variable name. For example you want to save name of hundred students in variables. It mean you have to make 100 variables. But it make your code so complicated and It is also time wasting. Instead of spending so much time on making variables you can store all 100 names of students in single variable using an array. In this tutorial we will learn basics of array like how to define an Array and how to Initialize an Array etc.

Arrays In PHP


In an Array values store using single variable name. But we use index number to add or fetch value from Array. For example you want to store name of hundred students in student Array. Then you have to add values like name of first student on the 0 index of student array, and name of next student on 1st index like this.

Defining and Initializing an Array: Defining an Array in PHP is so simple. The simplest way to define an array using array() function. Check the example below to understand it clearly.

Example





Fetching Values from Array: Fetching values from array is so easy there is print_r() function. By using this function you can fetch values and structure of array.

Example





In case you want to fetch values from array and see detail structure of array. There is another function var_dump() you can use this. Check program below to check var_dump();

Example





Types of Array in PHP:

There are total three types of array in PHP. We will try to understand each type of array using Examples. These three types are as follow
  • Indexed array
  • Associative array
  • Multidimensional array


Indexed array: Indexed Arrays are simple array in which we save values on index using array() function as we saw in our previous examples.

Example





Associative array: In associative array we save vales in key value form. For example "Ali"=>80, "Sameer"=>90, "Mohan"=>85. Check this program.

Example

80, "Sameer"=>90, "Mohan"=>85);

$marks["Ali"]=80;
$marks["Sameer"]=90;
$marks["Mohan"]=85;

print_r($stumarks);
print_r($marks);

?>



Multidimensional array: Multidimensional Arrays are also known as array of arrays. Mean instead of storing values on the index of an Array we save array on the indexes of array. Check the following example.

Example

 "ali",
        "marks" => 80,
    ),
    array(
        "name" => "Sameer",
        "marks" => 90,
    ),
    array(
        "name" => "Mohan",
        "marks" => 85,
    )
);

print_r($studentInfo);
?>





Share this tutorial with your friends on your social Media..

Arrays in PHP Arrays in PHP Arrays in PHP Arrays in PHP



Now You Can Follow All These Tutorials on Your Android Mobile Just Download This App.


Owlbuddy.com