Loading ...
Sorry, an error occurred while loading the content.

Tutorial: Problem & Solve (1st part)

Expand Messages
  • foysal foysal
    *Problem:** *Define a function which prints values of an array. *Solve (1st part):* * * A function is a named block of code that performs a specific task,
    Message 1 of 1 , Dec 10, 2010
    • 0 Attachment

      Problem:  Define a function which prints values of an array.

       

       

      Solve (1st part):

       

      A function is a named block of code that performs a specific task, possibly acting upon a set of values given to it, or parameters, and possibly returning a single value.

       

      To define a function, we use the following syntax:

       

      function  function_name ( [  parameter [, ... ] ] )

      {

      statement list

      }

       

      Notice the parentheses after the function name. These are required in a function call because they tell PHP that this is a function.

       

       

      Arrays are complex variables that store a group of values under a single variable name. An array is useful for storing a group of related values. So, we need something which can traverse through the values of the array, pick a value each time & print it accordingly. What can traverse through the values of the array? Is there something for that job?? What can do this special task? Yes, loops may do this task.

       

      If we name our function arrayprint and our array is $array then our function looks like below

       

      function arrayprint($array)

                {

                        

                }

       

       

      There are four ways to make code loop in PHP so that we can perform repetitive actions.

       

      The first loop type is called a while loop, evaluated repeatedly until it fails. We generally use a while loop when we don’t know how many iterations will be required to make the condition true.

       

      The basic structure of a while loop is

       

      while (condition) expression;

       

      If we require a fixed number of iterations, then we consider using a for loop. A more common form of loop is the for loop, and is slightly more complicated

       

      The basic structure of a for loop is

       

      for (expression1;condition;expression2)

      expression3;

       

      ·        expression1 is executed once at the start. Here we can usually set the initial value of a counter.

      ·        The condition is expression is tested before each iteration. If the expression returns false, iteration stops. Here we can test the counter against a limit.

      ·        expression2 is executed at the end of each iteration. Here we can usually adjust the value of the counter.

      ·        expression3 is executed once per iteration. This expression is usually a block of code.

       

      The third loop type takes the form do...while, and is similar to a while loop with the difference that it is always executed at least once.

       

      The general structure of a do...while is

       

      do

      {

         expression;

      }

       

      while ()

       

       

       

      The last type of loop is the foreach loop, and is used to loop through an array of data.

       

      The basic structure of a foreach is

       

      foreach (array_name as temporary_variable)

      {

      do something with temporary_variable

      }

       

      We are taking for loop for our task. First we need to know how many elements are there in the array. So that we can iterate our for loop that times.  There is a function in PHP to know the number of elements in an array and that is count (). Assume our array is $array. If we put our array in count (), then we will get  count ($array). Storing this value in a variable looks like this $num = count ($array);. We got the number of elements in our array and we can use it in our loop.  

       

      Now we are going to use our loop. We already got our limit to test the counter. We will use $num in this regard. If we write down our for loop it will look like this for ($i=0; $i<=$num; $i++). Our job is almost finished. At this moment we will print our values of the array. echo statement is helpful here. echo $array[$i];  this statement will print each value of the array one by one. Here, [$i] is the key of the value. But these values will come as horizontally, side by side. If we would like to get these values vertically we have to change the statement little. echo "$array[$i]<br>";   this will print elements vertically.

       

      At this point our function looks like below

       

       

      <? php

       

      function arrayprint($array)

                {

                         $num = count ($array);

                         for ($i=0;$i<=$num;$i++)

                                   {

                                            echo "$array[$i]<br>";

                                   }

                }

      ?>

       

       

       

      Now it is time to test our function. For test purpose we will take an array. That is   

       

      $state_capital= array ("Montgomery","Juneau","Phonix","Little Rock","Sacramento");

       

      If we test our function with the above array and call our function, the code will look like below

       

      <? php

       

      function arrayprint($array)

                {

                         $num = count ($array);

                         for ($i=0;$i<=$num;$i++)

                                   {

                                            echo "$array[$i]<br>";

                                   }

                }

               

      $state_capital= array ("Montgomery","Juneau","Phonix","Little Rock","Sacramento");

       

      arrayprint($state_capital);

       

      ?>

       

       

      The result is…….

       

      Montgomery
      Juneau
      Phonix
      Little Rock
      Sacramento

       

      We got our function which prints values of an array. Did we get the expected function?? What will happen if the array is like the below one??

       

      $director [4] ="Orson Welles";

      $director [1] ="Carol Reed";

      $director [93] ="Fritz Lang";

      $director [24] ="Jacques Tourneur";

      $director [] ="Alfred Hitchock";

       

      If we apply our function on the above array our code looks like below.

       

      <? php

       

      function arrayprint($array)

                {

                         $num = count ($array);

                         for ($i=0;$i<=$num;$i++)

                                   {

                                            echo "$array[$i]<br>";

                                   }

                }

               

      $director [4] ="Orson Welles";

      $director [1] ="Carol Reed";

      $director [93] ="Fritz Lang";

      $director [24] ="Jacques Tourneur";

      $director [] ="Alfred Hitchock";

                        

                        

      arrayprint($director);

      ?>

       

       

      The result is…….

       

      Carol Reed


      Orson Welles

       

       

      We did not get our expected result. There are 5 values in our array but we got 2, even the order is different too. Why this happens?? Answer is very simple. Our function first identifies how many numbers of items are there in the array. Then pick up values by their index. In this case our function has total 5 values. So it prints values which have keys from 0 to 4 sequentially. That’s why we got  Carol Reed first, because its key is 1. Then Orson Welles, because its key is 4. Other values are out of this function as their keys are not between 0 to 4.So what should we do now?? How can we solve the problem at this stage?? Yes, there is a solution, PHP has an array function named array_vaules () which extracts values from a given array and create another indexed array. If we use that function now we got a statement like this.

       

      $new_array= array_values($array);

       

      Now our function looks like below

       

      function arrayprint($array)

                {

                         $new_array = array_values($array);

                         $num = count ($new_array);

                         for ($i=0;$i<=$num;$i++)

                                   {

                                            echo "$new_array[$i]<br>";

                                   }

                }

       

       

      If we test our function the code will look like below.

       

       

      <? php

       

      function arrayprint($array)

                {

                         $new_array = array_values($array);

                         $num = count ($new_array);

                         for ($i=0;$i<=$num;$i++)

                                   {

                                            echo "$new_array[$i]<br>";

                                   }

                }

               

      $director [4] ="Orson Welles";

      $director [1] ="Carol Reed";

      $director [93] ="Fritz Lang";

      $director [24] ="Jacques Tourneur";

      $director [] ="Alfred Hitchock";

                        

                        

      arrayprint($director);

      ?>

       

      The result is…….

       

      Orson Welles
      Carol Reed
      Fritz Lang
      Jacques Tourneur
      Alfred Hitchock

       

       

      We got our expected function for this time. This function is also effective on other associative arrays.

       

      Further tutorial is coming next.

    Your message has been successfully submitted and would be delivered to recipients shortly.