Web Programming TutorialsVariables and Arrays in PHP

Variables and Arrays in PHP

Today we are going to learn about creating variables and arrays and use them in our programs. In last session we had learned to install xampp server on our computer to make it a local server. So now our computer or local server is now ready to run PHP programs.
Let us now start from variables in this Variables and Arrays in PHP tutorial.

  1. We know that to run PHP pages, we need to put it in the htdocs folder in the xampp folder located in C drive. So create a new folder named Var_Array in the htdocs folder.
  2. Open a new notepad++ document and save it as index.php in the newly created folder Var_Array in the htdocs folder.
  3. Now let’s open this page in the browser. For it you just have to write localhost/Var_Array in the address bar of the browser. Var_Array is the folder containing index.php page. No need to specify the name of page index.php, because it automatically runs the page having name index. The page in browser is shown below:
  4. initial_output
    fig 1

  5. Now write the following statement in index.php file.
  6. $x=5;
    • This is the variable declaration in PHP.
    • If you compare it with javascript, in javascript the variable declaration is as shown below:
    • var x=5;
    • The difference is that PHP does not use any keyword like var to declare the variable and variable name always starts with $ sign.
    • Now reload the page, output is shown below:
    • code_printed_as_it_is
      fig 2

    • Here in the above figure we can see that the PHP code has printed as it is.
    • This is because the tag is not being used. So put the above code in
      <?php?>

      tag as shown below and then see the output.

    • <?php
      	$x=5;
          echo $x; 
      ?>
    • It will work even if you omit ?>.
    • Here, $x=5; is the variable declaration and echo $x; is the statement used to print it on the webpage. Keyword echo is used to display anything i.e. a string or value of a variable.
    • Every statement ends with a semicolon.
    • The output is shown below:
    • value_of_var_printed
      fig 3

  7. Printing a string is very simple. Write the following code:
  8. <?php
    echo 'Any String';
    ?>
    • Here, echo ‘Any String’; statement will print Any String on the page. The string to be printed can be enclosed in single quotes or double quotes.
    • Output is shown below:
    • String_printed
      fig 4

  9. Concatenating values of 2 variables:
    • Write the following code in index.php file:
    • <?php
      $word1='Hello';
      $word2='World';
      echo $word1.' '.$word2;
      ?>
    • Here, $word1 variable contains string Hello and $word2 variable contains string World.
    • To concatenate values of two or more variables and strings in PHP we use period(.).
    • So in the above echo statement we have concatenated both the variables with a space in between using a period.
    • Output is shown below:
    • concatenating_2_variables
      fig 5

    • Now I will just add another string before Hello World in the above code.The changed code is shown below:
    • <?php
      $word1='Hello';
      $word2='World';
      echo 'I just want to say '.$word1.' '.$word2;
      ?>
    • Here, I have added a string “I just want to say”. The output is shown below:
    • string_concatenated_to_variable
      fig 6

  10. Now let us add two variables.
    • Write the following code inside
      <?php?>

      tag:

    • <?php
      $num1=5;
      $num2=7;
      echo $num1+$num2;
      ?>
    • Here, the numbers 5 and 7 stored in variables $num1 and $num2 are added using arithmetic addition operator(+).
    • Output is shown below:
    • 2_nos_added
      fig 7

    • If you want to write some string before the addition, follow the code:
    • <?php
      $num1=5;
      $num2=7;
      echo "Sum of 2 numbers = ".($num1+$num2);
      ?>
    • Here, we have added a string “Sum of 2 numbers = ” to the addition of variables using a period.
    • During this make it sure that you put your variable addition in the parenthesis like ($num1+$num2), otherwise instead of the sum of 2 variables only the value of second variable will be printed.
    • The output is shown below:
    • string_added_to_sum_of_2_variables
      fig 8

    • In this way we can work with variables.
  11. Now let us work with arrays.
    • Array is nothing but a collection of values stored in a single variable.
    • Declaration syntax of an array is done as follows:
    • Variable_name= array(val1,val2.val3);
    • Eg: $fruits=array(‘apple’,’mango’,’banana’,’grapes’);
    • Write the following code in the index.php file:
    • <?php
      $cars=array('Honda','Toyota','Ford');
      echo $cars[0];
      ?>
    • Here, we have declared an array of $cars having values Honda, Toyota and Ford.
    • In PHP also like JavaScript the start index of array is zero(0).
    • So echo $cars[0]; statement prints the value at index 0 i.e. Honda.
    • The output is shown below:
    • array_value_printed
      fig 9

    • We can also concatenate a string with an array value as shown below:
    • echo 'I drive a '.$cars[2];
    • Here we have concatenated a string “I drive a ” with the $cars array value located at index 2 i.e. Ford.
    • The output is shown below:
    • string_concatenated_with_array_value
      fig 10

  12. Traversing whole array with a foreach loop.
    • In PHP most of the times it is feasible to use foreach loop.
    • Let us write the following code:
    • <?php
      $cars=array('Honda','Toyota','Ford');
      foreach($cars as $car)
      {
      	echo $car.'<br/>';
      }
      ?>
    • Foreach loop is written using the foreach keyword.
    • It contains the name of the array whose values are to be displayed, a keyword as and any variable to traverse through the array .
    • In the above case, array whose values are to be displayed is $cars and the variable used to traverse through the array is $car.
    • The statement inside the foreach loop is
    • echo $car.
      ;
    • This statement is used to print the array values fetched by the variable $car. Brake tag is concatenated to give a line brake.

    • In foreach loop the variable $car fetches the value at index 0 of $cars array which is printed using echo statement. It then automatically points to the next index i.e. index 1 and displays the next value in the array. It repeats this process till the end of the array.
    • The output is shown below:
    • array_values_printed_using_foreach_loop
      fig 11

    • If you add one more value to the array $cars, it will also be printed.
  13. Now let us learn about an array having not only a value but also a key.
    • These arrays contain a key value pair.
    • Let us learn it by declaring it and accessing it s value. Write the code shown below in index.php page:
    • <?php
      $car=array('make'=>'Toyota','model'=>'Camry','color'=>'Black');
      echo $car['make'].’<br>’;
      echo $car['color'];
      ?>
    • The declaration of array $car is shown above.
    • It contains key value pairs separated by a comma.
    • In the above array, make is a key and Toyota is its value, similarly model is a key and Comry is its value and so on.
    • A value is associated with the key using => sign.
    • The values are accessed using the keys as shown above.
    • The output is shown below:
    • key_value_pair_array
      fig 12

  14. Displaying key-value pair array values using foreach loop.
    • Write the following code in index.php file:
    • <?php
      $car=array('make'=>'Toyota','model'=>'Camry','color'=>'Black');
      foreach($car as $key=>$value)
      {
      	echo $key.' : '.$value.'<br>';
      }
      ?>
    • For the key – value pair array there is a slight difference in using foreach loop.
    • In the above foreach loop $car is the array whose values are to be displayed, as is the keyword and there is a variable used $key for the key in the array and $value for the value of the key in that array. And this key value pair in the foreach loop is written in the same way as written in the array.
    • Next we have displayed the keys as well as the values from the array in the echo statement.
    • The output is shown below:
    • foreach_loop_for_key_value_array
      fig 13

    • If we want to capitalize the initail letters of the keys, use ucwords() function in the echo statement as shown below:
    • echo ucwords($key).' : '.$value.'<br>';
    • Here, we have given $key as a parameter to the function ucwords(). This will capitalize the first letter of all keys.
    • The output is shown below:
    • capitalized_first_letter_of_keys
      fig 14

    • These arrays are sometimes called hashes in other languages.

Thus we finished learning to use variables and arrays in this Variables and Arrays in PHP tutorial.

Previous articlePHP Environment Setup
Next articleMovie Select Project

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -