Array and foreach loop in PHP

In this tutorial, we will study about array and foreach loop. Let's assume you have to store large data, for example first 10000 multiples of five. Then you will have to define 10000 variables with 10000 names. It will make your task very tough. One of the solution is storing data in array. We can store many values just in single array. Let's take a look how?

  1. <?php
  2. // defining an array with three values
  3. $type1 = array('first element', 'second element', 'third element');
  4. // for printing full array we use print_r function
  5. // display => Array ( [0] => first element [1] => second element [2] => third element )
  6. print_r($type1);
  7. echo "<br>";
  8. // for printing single element we use indexes
  9. // for $type1 indexes are 0, 1, 2
  10. echo $type1[0];
  11. echo "<br>";
  12. echo $type1[1];
  13. echo "<br>";
  14. echo $type1[2];
  15. echo "<br>";
  16. ?>
  • In line 3, we are defining an array (named $type1) and filling 3 values ('first element', 'second element', 'third element') in it.
  • Now how will we use it? Every value is mapped to an unique identity, called index. We will access these values via indexes. Line 7 is printing the array using print_r() function. You can see that you have filled just values but you are getting that numbers starting from 0 are mapping to those values. In fact these are position number (in programming position starts from 0 instead of 1).
  • In line 13, 15 and 18, we are printing the values which we have stored on the position 0, 1 and 2 respectively.

Associative array:

In above example, we use the default indexes ( 0, 1 and 2). We can also define our own indexes just like in this example.

  1. <?php
  2. // second type to define array
  3. $type2 = array('key'=>'value','key2'=>'value2','key3'=> 'value3');
  4. // display => Array ( [key] => value [key2] => value2 [key3] => value3 )
  5. print_r($type2);
  6. echo "<br>";
  7. //for $type2 indexes are key, key2, keys3
  8. echo $type2['key3'];
  9. ?>

Here we are also defining own own indexes (keys) which are mapped with values. This types of arrays are called associative array.

Accessing the arrays:

Every value in the array is an individual variable. We can operate all operations which we can do on variables ( like addition, subtraction, assigning values, etc.)

  1. <?php
  2. // we are defining an empty array (no data)
  3. $arr = array();
  4. // we can assign data like this
  5. $arr[0] = 'harish';
  6. $arr[1] = 'kumar';
  7. // we can also skip indexes ( there is no 2 and 3)
  8. $arr[4] = 'jump';
  9. // we can use both types of indexes in same array
  10. $arr['day'] = 'Monday';
  11. $arr['num1'] = 4;
  12. $arr['num2'] = 5;
  13. // each variable is independent
  14. $arr['num3'] = $arr['num1'] + $arr['num2'];
  15. // printing array
  16. print_r($arr);
  17. ?>

Note: We can define array inside an array itself. It is called multidimensional array. For example:

$a = array(1, array(2, 3), 4);

Array with loops:

Lets assume we have to do some operation on a large data stored in array (say printing data or adding numbers). For this work we will use loops. Now take an example of for loop:

  1. <?php
  2. $a = array(1,21,23,43,32,23,4);
  3. // our variables are $a[0], $a[1], $a[2]........
  4. // initially sum is 0
  5. $sum = 0;
  6. for($i = 0;$i<7;$i++)
  7. {
  8. // i will increase 1 every time, i.e. position of array will shift
  9. // 1 every time in loop
  10. $sum += $a[$i];
  11. }
  12. echo $sum;
  13. ?>

This is your exercise to do this example using while and do while loop.

There is one more loop in PHP, specially for array, called foreach loop. Foreach loop is a loop which start some operation from first element (data) and does up to last element. Lets do above example with foreach loop.

  1. <?php
  2. $a = array(1,21,23,43,32,23,4);
  3. // our variables are $a[0], $a[1], $a[2]........
  4. // initially sum is 0
  5. $sum = 0;
  6. foreach ($a as $v) {
  7. // in each iteration we are doning something like this
  8. // $v = $a[$i];
  9. // $sum += $v;
  10. // i++;
  11. $sum += $v;
  12. }
  13. echo $sum;
  14. ?>

Here we are defining a new variable $v each time and giving the value of next element of $a. Foreach loop is useful when you don't know how many elements are in the array or when you are using associative array.

Foreach loop with associative array:

In the case of associative array we have to define two variables (instead of one) because we don't know the index (key) for each element. First variable is the index and another is value mapped with it.

  1. <?php
  2. $a = array('name'=>'harish','soms' => 'word','somemore' => 'title','author' => 'harish','last' => 'kumar');
  3. foreach ($a as $k => $v) {
  4. // observe the value of $k and $v
  5. echo "key is $k and value is $v <br>";
  6. }
  7. ?>

If you find any difficulty in this tutorial or you have some suggestion then please leave comment. In next tutorial we will study about the operations on the arrays.

Don't forget to Subscribe for latest feeds.

Comments and feedback are welcome.

Show full series till now

Go Back To Last Tutorial



About Harish Kumar

Harish is an interested person in the field of web development and blogging. He works for the need of young web developers in learning various languages, latest technologies and other essential tips and tricks. If you need some help or you have some suggestion then you email him at harish@findalltogether.com without any hesitation. You can also suggest/demand for articles of your own choice.

Related Articles

In this part of free tutorial series, I am telling you about syntax, variables, data types, comments, constants and o...
Introduction to PHP
In this part of free step by step tutorial series I will teach you about for loop, while loop and do while loop of PH...
loops in PHP
In this part of free step by step tutorial series I will teach you about if, if else, nested and switch statements of...
Conditional statements in php

Login or Sign up to leave comment.