Numeric array

A numeric array does not mean it only holds numeric data. In fact, it means the indexes will be numbers only. In PHP they can either be sequential or non-sequential but they have to be numeric. In numeric arrays, values are stored and accessed in a linear way. Here are some examples of PHP numeric array:

$array = [10,20,30,40,50]; 
$array[] = 70;
$array[] = 80;

$arraySize = count($array);
for($i = 0;$i<$arraySize;$i++) {
echo "Position ".$i." holds the value ".$array[$i]." ";
}

This will have the following output:

Position 0 holds the value 10 
Position 1 holds the value 20
Position 2 holds the value 30
Position 3 holds the value 40
Position 4 holds the value 50
Position 5 holds the value 70
Position 6 holds the value 80

This is a very simple example where we have an array defined and indexes are autogenerated from 0 and incremented with the value of the array. When we add a new element in the array using $array[], it actually increments the index and assigns the value in the new index. That is why value 70 has the index 5 and 80 has the index 6.

If our data is sequential, we can always use a for loop without any problem. When we say sequential, we do not mean just 0,1,2,3....,n. It can be 0,5,10,15,20,......,n where n is a multiple of 5. Or it can be 1,3,5,7,9......,n where n is odd. We can create hundreds of such sequences to make the array numeric.

A big question can be, if the indexes are not sequential, can't we construct a numeric array? Yes definitely we can. We just have to adopt a different way to iterate. Consider the following example:

$array = []; 
$array[10] = 100;
$array[21] = 200;
$array[29] = 300;
$array[500] = 1000;
$array[1001] = 10000;
$array[71] = 1971;

foreach($array as $index => $value) {
echo "Position ".$index." holds the value ".$value." ";
}

If we look at the indexes, they are not sequential. They are having random indexes such as 10 followed by 21, 29, and so on. Even at the end we have the index 71, which is much smaller than the previous one of 1001. So, should the last index show in between 29 and 500? Here is the output:

Position 10 holds the value 100 
Position 21 holds the value 200
Position 29 holds the value 300
Position 500 holds the value 1000
Position 1001 holds the value 10000
Position 71 holds the value 1971
Couple of things to notice here:

We are iterating the array the way we entered the data. There is no internal sorting of the indexes at all, though they are all numeric.
Another interesting fact is that the size of the array $array is only 6. It is not 1002 like C++, Java, or other languages where we need to predefine the size of the array before using it, and the max index can be n-1 where n is the size of the array.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset