Arrays in php are just like we give single name for multiple variables. When we are dealing with data mostly, we have a group of data but we want to bind all that data in one name e.g., student/employee record we have name, email, address, phone number and password now we want to give it one name and can have unique access to inner data. let's create an array.
$user=array("name"=>"Ali Raza", "email"=>"ali@gmail.com", "address"=>"ABC Road", "password"=>"123");
in above example of arrays in php i have created one array and name it "$user" and it's had four inner variable name, email, address and password. After declaring the array, we need to access this array with variable names.
if we note we have multiple values in array with comma separated like ("name"=>"Ali Raza") so you can add as much as you needed.
If we want to all array, we use it or when we are fetching data from database, we get array then we need to check what data coming so in developer end we print it. Sometime we think there is data but actually there is no data coming due to some issue so this command will give us great help to check data is coming or not.
print_r($user); // this will print all array
After declaring the array, we need to access this array with variable names. if we want to print single variable, we use echo or print command
echo($user["name"]); // it will print Ali Raza
print($user["email"]); // it will print ali@gmail.com
if we want to change values in arrays in php
$user["name"] = "Imran Minhas";
// if we print it we will get new value like
echo($user["name"]); // it will print Imran Minhas
if you want to add more variable in array e.g. After declaring the user array, you get ID Card number now you need to attach this ID Card number in above array.
$user["ID_Card"]="1234567890";
again, you can check it with print_r command and you will see your newly added variable with value shown in the array.
Some time we have arrays that's don't need inner variable name like name of cities then we use simple (index array) array and don't give inner variable name like.
$cities = array("Jhelum", "Dena", "Multan", "Pindi", "Sarghoda");
We call this index array and this is index it with number and number start from 0,1,2,3 so on 0 index Jhelum is saved on 1 index Dena is saved and so on. We can use print_r to print all array.
// print all Array
print_r($cities);
// print single index
echo($cities[0]); // will print Jhelum
// change index value
$cities[1]="Sialkot"; // Dena will replace with Sialkot
One point if you note above array having string name and when we give it is inside the quotes but when we are calling index array it has no quotes.
$user["name"] = "Imran Minhas"; // name is inside the quotes
$cities[1]="Sialkot"; // 1 having no quotes
This points you will see on other a lot of programing codes string come with quotes and number without quotes.
If you have any questions, you may ask me in the comments box, I will try to reply to you with the best answer.