Tuesday 18 October 2016

Beginner Approach to Arrays in PHP

Hello!!! It’s time to learn again. As I have made it clear before, I will make sure that I explain every topic in a way that a complete beginner would understand.
PHP ARRAYS
Arrays are special types of variables. They are special variables because they can hold more than one variable at a time unlike variables
which can only hold one value at a time.
Let us have an example: We have a list of ten students in a class for instance, if we are going to put them in variables, we would have something like this:
$person1 = "Ola";
$person2 = "Cindy";
$person3 = "Sodeeq";
$person4 = "Ezekiel";
...and so on till the last person.
Instead of going through this stress, arrays make it easier for us to group data that are of the same type (be it numbers (integers or floating point numbers, strings (sequence of characters), among others).
So in case of Arrays now, we are going to have just a single holder for our values.
Arrays take the form:
$persons = array("Ola", "Cindy", "Sodeeq", "Ezekiel");
With the line above , we have declared an array and assigned values to it.
Note that the values entered are of the same type (String).
So what? I have an array now, next thing?
The next thing to do after creating your array is to access the elements of the array.
Array elements are accessed with their indexes, and the index of an array element is that element's current position minus 1. That is to say, if the element is the second in the list, its index is 2 - 1 = 1 and it will be accessed as such.
How to access Array elements?
From the example above, you can access each element of the array $persons with their index as shown below:
$persons[0]; this will display Ola
$persons[2]; this will display Sodeeq
...and so on.
How is this different from writing the variables separately?
You can print all the elements in an array using the for-each loop, that will be treated later.
Till then, if you have any questions(s) you can ask.
Coding is Fun!

No comments:

Post a Comment

Your response mean a lot to us. Drop one.