What is an Array?  Positions and Values in Array How to output array values using positions? Indexed Array & Associative Array Count Values of an Array What is for each loop?

Day 5

Hello and welcome to PHP – in 15 Days – Guaranteed Training Course. Today we’lllearn about arrays, what are these and how we create and store data in these, how to get data out of these and how we can sort them? Also,today we’ll learn about the final type of the loops i.e. for-each loop.

·         Arrays (Index and Associative Arrays)

·         Sorting Arrays

·         For-each Loop (Loop to Handle arrays)

What is an Array?

An array isa special kind ofa variable that is capable to hold more than one data of same or different data types at the same time. To demonstrate it let’s have an example,

Take a look at agigantic truck like container which is used to transport cars or different vehicles from a factoryto many other places. Take a look at it. It’s containing different types of vehicles at the same time. Each vehicle is placed at some specific place and has its own identity. You can say this container is an array. All the vehicles are data packets of different or same type and every data is fixed and setat some specific position. Now in terms of PHP we say a value to the vehicle in this example.




Syntax:

To define an array let’s create a new variable just like wecreated several variables before, but this is going to be an array.

      $my_array = array(2,3,6,7,9,10);

 

Let’s create our first ever array. Name it my_array and instead of defining the value of this variable right after equals sign we need to tell that this is going to be a special variable and that is array, just put ‘array’ keyword and start parentheses.Between these parentheses we are placing vehicles i.e. values of this array. So, put the data here by separating each data or value with a comma and just close at the end. Now, let’s echo our array to seethe output, but it’s giving an error, but here you can see that PHP is telling us that it’s an array. The variable you want to echo is a special kind of variable.That’s why, we cannot echo an array directly.

      echo$my_array;

 

As we discussed before it’s a special kind of variable i.e. it’s an array. How we will output it, we’ll see this in a moment.For the moment I just want to show you, what is there inside this Array.For this purpose, I need to use a built-in-function and that is var_dump just to show you an insight of the array.

      var_dump($my_array);

 

Here we go, it shows us some output, and another way of viewing array is print_r.

      print_r($my_array);

 

You can use either of these just to view the data of an array.Both of these are mainly used to de-bug or to check the data and positioning of datain an array. So, this is how we createan array.

Positions and Values in Array:

Now let’s move a little further and just take a look again at our output closely.

Just make little changesin the array to better understand it.Let’s use pre tags to make the output more readable. OK



$my_array = array(3, 5, 7, 9, 11);

//echo $my_array;
echo '<pre>';

print_r(
$my_array);

echo '</pre>';

 

Let’s go to the browser and here is the output of the array we just created. You can see at position 0 the value is 3, at position 1 value is 5, at 2 value is 7, at position 3 value is 9 and at position 4 value is 11. So, this square brackets and the integers within square brackets are positions of concerned data. Concerned data is the only one data which is pointed by equals and greater than sign which actually points to the value. Any array in which we just define values, have positions in integers and the positioning starts from 0.

Array
(
    [0] => 3
    [1] => 5
    [2] => 7
    [3] => 9
    [4] => 11
) 

 

 

So, always remember that in every array values have their own position and these positions are actually called keys. So, every array has set of key-value pairs.

How to output array values using positions?


Now we want to call or extract any specific value from the array. We know that each value is bound to its key and keys in an array start from 0. So we have 5 values and 4 keys starting from 0. First key is 0. So to get any value from array we write name of the array and then between square brackets, like we saw in our output before, write the key of specific value.

Let’s just try to echo some of the values from the array. If we put the key 1 here, I expect you to guess the right value now,……………………

echo$my_array[1];

and it’s obviously 5. Let’s check this out in browser and you can see it’s 5. Above here you can see value 5 bound to the key 1. Let’s just copy and paste and change the key here to 2 and that’s 7. So, you can define any key here within the array and it will show us the value of that key.Just echo the br tag between these.

Now if we ask for the key which is not in the array, as in our array we have only 5 values and keys starting from 0 to 4. So, let’s try to echo value of key 5 which is off-course not available.

echo$my_array[5];

Let’s go to the browser and you can see

Undefined offset: 5 in C:\xampp\htdocs\phpin15days\day5\array.php on line 22

error message and that’s rightly so. It means the key 5 doesn’t exist at all. So, remember whenever you get undefined-offset error message for an array you are making some mistake while keys manipulation.

Let’s change the key to 4 and that is available and we will get 11.


echo$my_array[4];

 

You can see 11 as the output. So, this is how we can use keys to echo or get the concerned value from an array.


Indexed Array & Associative Array:

Indexed Array:

There are actually three types of array but we will discuss two types only as the third one is more complex and I don’t want to confuse you at this stage of learning. Indexed array is an array in which we just define the values and PHP automatically allots positions to these values from 0 to end of the values. Simply remember that where you don’t define keys or positions to the values is an indexed array.

      $my_array = array(3, 5, 7, 9, 11);

 

Let’s get back to our array we created before and you can see, we just defined values and there is no key you can see.But when we observe the output using print_r, you can see every single value has a position or key attached to it, starting from 0 to so on till the end of values. This type of array is an indexed array.



Associative Array:

To understand let’s create a new array called ages. Let’s just put some different values, 35, 55 and 90. This is another indexed array right now. You can check it by outputting it, but let’s first manually assign keys to these values. 0, 1 and 2 although these values are already bound to these keys,

      $ages = array(0=>35, 1=>55, 2=>90);

 

but lets just do it. Let’s ‘print_r’ and see the output, so, its same as for indexed array, nothing has changed. Now let’s change keys for each value. Let’s make 7, 9 and 30 and output it.

      $ages = array(7=>35, 9=>55, 30=>90);

 

Here you can see the keys or positions are changed now and these are according to our own desire. So, this is an example of associative array. We have manually assigned keys of our own choice to the values and are not using original keys. So, whenever we associate keys to the values, array becomes associative array.

Now, instead of numeric keys, we can put stringsas well. Let’s do it now.

Let’s set the key Ben for value 35, shawn for 55 and micheal for 90.

 
      $ages = array('Ben'=>35, 'Shawn'=>55, 'Micheal'=>90);

 

Let’s check the output for this array now. Refresh the browser and you can see the keys have been changed to strings as we defined them. So, now we can echo any value by declaring its string key. Let’s try it for Ben

      echo$ages['Ben'];

 

Here we go, 35, you can go ahead and check out all of these one by one. Just keep notice of string, when you need to declare it enclse it within single or double quotes.

Count Values of an Array:

What if you want to know how many values are there in an array? For this purpose we can use a built in function count to count the values in an array. Let’s just create a variable ‘total_value’. This will store the total number of values in our ‘ages’ array. Just write ‘count’ that is the internal function and start parenthesis. Within parenthesis we pass the array for which we want to count the values, so, just pass ‘ages’ array here.



      echo$total_value = count($ages);

 

echo it out we will get total number of values within this array. Here we go it’s 3.

 

 

How to Output Values of an Array:

As we’ve already discussed that array is a special kind of variable that holds several values at the same time, so, it’s known as an array. To grab the value out of its values, is not that straight forward as variable, but still it’s an easy and simple task. Here we’ve both of the arrays.First one, my_array, is an index array and second one is an associative array.

$my_array = array(3, 5, 7, 9, 11);
$ages = array('Ben'=>35, 'Shawn'=>55, 'Micheal'=>90);

 

Let’s addsome pre tags, so thearraysare more readable to us. Let’s just view them in our browser by print_r. Here you can see that indexed array has integer keys following an order 0 to end of the values but associative array has only strings we defined as keys.

echo'<pre>';
print_r(
$my_array);
print_r(
$ages);

echo '</pre>';

 

Let’s try to get a value for the key 0 as keys start from 0 in any array.

      echo$ages[0];

 

Here we get an error

Undefined offset: 0 in C:\xampp\htdocs\phpin15days\day5\output_arrays.php on line 22

It means PHP couldn’t find any key that is equal to 0 in ‘ages’ array. So, if we want to get any value from ages array we must mention the exact key because we manually assigned the keys and made this array an associative array. The second option to get all the values out of an associative array is to use a loop which is especially meant to work with arrays and that is ‘Foreach-Loop.’ We will study this loop today later.

However, if we want to get some value from my_array which is an indexed array, it’s absolutely possible.Let’s just echo the value at key 0.

      echo$my_array[0];

 

We easily get the value 3 which is at 0 position in my_array. Also, you know that ‘my_array’ is an indexed array, so, all the keys are integers from 0 to end of the values maintaining the sequence, so we can easily output associated values by using for or while loop.  

Let’s just create simple for-loop. Define variable x and make it equals to 0 as keys in an array starts from zero. Now before doing condition check lets count all the values in our indexed array by count and store total values in variable y. Now make the conditional statement to run the loop until the values end and finally increment the variable x to stop the loop at end of the values.

      for($x = 0; $x <$y; $x++)

 

Within the execution area,I am just going to echo the value as we did for a single value and besides hard-quoting the key within square brackets I just pass the variable x here.

      {
echo$my_array[$x];
echo '<br>';
      }
 

So, what’s the purpose of this variable x here. On each iteration of loop $x will be added by one and will echo the value of that relative position. In first iteration key will be 0 as x will be 0, in second x will be 1 so the key will be 1 and so on. This loop helped us in doing the same work for 5 times. Now, let’s go to the browser and have a look at the output. Here we go, we have all the array values in our output.

Sorting Arrays:

At many occasions we might be in need to rearrange arrays. To rearrange arrays we sort them in different ways in PHP by using very simple internal-functions. Sorting procedure can sort the values as well as keys of an array in any direction (ascending or descending) we want.

Let’s start with two arrays, little different from our previously defined arrays. I made changes in values so that sorting of arrays can be observed and understood easily. So, now we have two arrays here.




‘my_array’ and ‘ages’

      $my_array = array(3, 67, 5, 7, 22, 9, 11);

$ages = array('Ben' =>35, 'Dean' =>72, 'Shawn' =>55, 'Micheal' =>90);

‘my_array’ is an indexed array and ages is an associative array. For sorting arrays we have many built in functions with the help of which we can easily sort arrays according to our requirement. Let’s start with assort(). Sorting with this function will sort the values from lowest to highest values, keeping the keys intact with the relevant values. Just call the function and don’t try to store this to anywhere, and when you’ll output your array, it would’ve been sorted.

      asort($my_array);
 

and now just print_r ‘my_array’ to have a look in the browser

      print_r($my_array);

 

Now you can see that array has been sorted arranging the values from low to high and all the keys are intact with the values. Key 0 is at top but key 1 is the last as values of key 1 got the last position due to sorting of values. Sequence of values is in ascending order now.

Now let’s do the same asort() with our associative array.

      asort($ages);

 

and

      print_r($ages);

 

here we go it’s sorted now, value wise from lowest to highest, however, the keys are intact with their values.

Now lets try arsort on the same pattern we have, this function is reverse of asort, as it will sort the values from highest to lowest and keys will remain intact.

arsort($my_array);
arsort(
$ages);
 

and just view the output in browser and here we go all the values have been sorted out value wise in descending order and all keys are associated with values. Same for ages array and you can see associated keys are intact but values have been sorted.

If you want to sort arrays by their keys only, you can use ksort and it will sort array by keys from lowest to highest. Let’s try this

ksort($my_array);
ksort(
$ages);

 

Check this out in browser and you can see here, keys have been sorted for indexed array from 0 to 6 and in associative array keys are sorted alphabetically from a to z, and all the values for both indexed and associative arrays are intact with keys.

Krsort another sorting function. This is the reversal of ksort. This function sorts array by keys from highest to lowest while values remain intact. Let’s quickly try this.

krsort($my_array);
krsort(
$ages);
 

And here we go, all the results as expected. Reverse sort means from highest to lowest that is descending order by taking keys in consideration. I recommend you to visit php.net for more information and details on sorting arrays and don’t forget to practice these.

For-Each Loop:



What is for each loop?

We have studied different types of loops. Now we are going to learn the last and final type of loops that is for-each-loop. For each loop is a special one. This loop works only with arrays. We pass an array to it, and this loop keeps onlooping through all the values of this array. As soon as the values are ended up, this loop automatically stops. In each iteration, for-each loop outputs one value or one key-value pair from the array.

Let’s try to understand by an illustration:

Here we have an array ages, with 3 values at three keys. When we pass the array to for-each loop it will take three iteration in total as array has three values. In first iteration loop will output first key/value pair i.e. Ben and 35, in second iteration for-each loop will output Dean and 72 and in third and final iteration it will outputshawn and 55. This is how for-each loop works. The output depends on our requirement, we can either get key-value pairor  keys only or values only.Now, let’s do it practically.

Here we have our previously defined array ages with three key/value pairs.

      $ages = array('Ben' =>35, 'Dean' =>72, 'Shawn' =>55);

 

Now let’s start for-each-loop by keyword foreach and parenthesisright after it, and between these let’s pass our array to foreach-loop. Now foreach-loop knows, it has to loop through all the key/value pairs of this array and know how many iterations it has to take. Now, we want, just for the moment, only values means 35, 72 and 55.

foreach($ages as $value){
echo $value;
echo '<br>';
}

 

So, use the word ‘as’ and right after tell foreach-loop what to show, with a variable. So, this variable will store the values temporarilyfor each iteration and will output that. In this case 35, 72 and 55. Let’s just echo it out and put a line break to show each value onnew line. There we go, all the values have been extracted and displayed. Now we need the keys too. Let’s get these too. Here we need to put same pointing notation which we used in associative array to make key/value pair. It will tell foreach-loop that we need key as well as value, both.

foreach($ages as $key=>$value){
echo $key;
echo ' : ';//just separator
echo $value;
echo '<br>';
}

 

Now we have the output of keys too, let’s just echo our keys too. Put a separator between to make it more readable. Let’s see our output in the browser and as expected all the keys with values displayed line by line. So, what we did here is, we passed our array ages to foreach-loop, and told foreach-loop to use ages array, and give us as key/value pair on each iteration.

This is how foreach-loop works and how we can use it precisely. I want you to practice it several times until and unless you are familiar and quite used to of this. This is all for day5, see you on day6.

Assignment:

1.       Create three different indexed arrays containing 5 to 10 values in each array.

2.       Output each of the arrays using for-loop

3.       Output each of arrays using while-loop

4.       Output each of arrays using do-while-loop.

5.       Create an associative array of greetings (values) and days (keys). Declare a variable and you can keep it equals to any name of the day. Now, whenever the name of the day for variable is changed, your script should display relevant greetings message from the associative array. (You are free to choose anything for your keys and values from greetings or days. It’s up to you.) 


Practice files Day #5

         Download 





Related Posts:

Leave a reply

Required fields are marked *

Login to Post Comment