PHP for Beginners – Part 3
Hey Folks! In this part of the tutorial we will be seeing how to create functions, play with single and multidimensional arrays and String related functions. These are the backbone of any programming language. Almost 80% of time when we code we will be needing them. All of you young learners put full effort in this section.
Functions
Definition: Function is a block of code used for perform a specific task.
Why and When we use function? Let’s take an example where you need to wake up early and you tell your mother/father/friend to wake you up early in the morning. So as being asked they wake you up that day. But let’s take a case where you have to wake up early on daily basis. Ask them for the favor, I guess you better know the results. So In that case you set an alarm in your phone or watch. So that is what function is all about, to do a task repeatedly without coding it over and over.
See the syntax for writing a function.
1 2 3 4 5 6 |
// general syntax function <function name >(optional_argument, another_optional_argument) { statements; statement; optional return value; } |
Have a look at the example below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php // create a function to calculate cube of a triangle function cube($area) { return $area * $area* $area; } // create a function with default value function cube2($area=3) { return $area * $area* $area; } echo "The cube of area is ". cube(10)."<br>"; echo "The cube of area is ". cube(40)."<br>"; // example of default parameter echo "The cube of area is ". cube2()."<br>"; ?> |
By default PHP provides rich sets of function that makes our lives easier. Some of them are listed below, to search for a specific function visit the PHP site.
1 2 3 4 5 |
<?php echo abs(-20); //returns the absolute value 20 echo substr("Manhattan", 0, 3); // returns a sub string of the text i.e. Man echo length("test") // returns the length of the string ?> |
Tips: Whenever you have to write a code with more than 10 lines, or a common code that will be needing more than once place the code under a function.
Arrays
Definition: You already know about variable. Array is nothing but a sequence of variable of similar or dissimilar type.
Explanation: You can say, Array is a container that can hold many variables. The starting index is zero and ends with (n-1). Associative array is marked with key and value. Remember a key must be integer or string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<?php $arr = array(10,20,30,40,50); echo $arr[0]; // prints 10 echo $arr[3]; // prints 40 // printing array value using for loop for($i=0; $i < count($arr); $i++ ) { echo "Index $i has value ". $arr[$i]."<br>"; } // associative array $arr = array("name" => "David Beckham", "age" => 38, "country" => "England"); echo $arr["name"]; // prints David Beckham echo $arr["age"]; // prints 38 // printing associative array foreach($arr as $key => $val ) { echo "Key <b>$key</b> has value <b>". $val."</b><br>"; } ?> |
Multi Dimension Arrays
There are cases where we have an array that contain an array, In that case we called it multi dimension array or array of arrays.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?php $arr = array( "england" => array("David Beckham", "John Terry", "Rio Ferdinand") , "spain" => array("Fernando Torres", "Iker Casillas", "Sergio Ramos") , "argentina" => array("Lionel Messi", "Javier Mascherano", "Gonzalo Higuain") ); foreach($arr as $key => $country ) { echo "<u>Team $key</u><br> "; // print_r($country) /* uncomment it to see the value */ foreach($country as $player ) { echo $player."<br>"; } echo "<hr>"; } ?> |
Commonly used array functions. See all functions here
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php $arr = array("name" => "David Beckham", "age" => 38, "country" => "England"); echo count($arr).'<br>'; // prints 3 echo sizeof($arr).'<br>'; // alias of count var_dump( in_array(38, $arr)); // returns true if value exists in an array echo "<br>"; var_dump( is_array($arr)); // returns true if variable is array else return false echo "<br>"; sort($arr); // sort an array var_dump( array_key_exists("age", $arr)); // returns true if key exist else return false $res = array_merge (array( "club" => "psg"), $arr); echo "<br>"; print_r($res); // merge arrays into one ?> |
Strings
String is a series of character. Same as arrays it also has got index from which we can get the value of that particular index. Look at the example below you will get to know what I am talking about.
1 2 3 4 5 6 7 8 9 |
<?php // define a string $str = 'This is a test string'; #echo $str; for ($i = 0; $i < strlen($str); $i++ ) { echo $str[$i]; } ?> |
Most commonly used string function. See all functions here
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php $str = 'This is a test string'; echo strlen($str)."<br>"; //returns the length of the string echo addslashes($str)."<br>"; // add slashes to the string to avoid sql injection echo stripslashes($str)."<br>"; // strip the slashes to properly display the output // Strip whitespace (or other characters) from the beginning and end of a string echo trim($str)."<br>"; echo strtoupper($str)."<br>"; // Make a string uppercase echo strtolower ($str)."<br>"; // Make a string lowercase echo substr($str, 0, 4)."<br>"; // returns a part of the string var_dump( strcmp($str, "test")); // perform comparison between two string echo "<br>"; echo strip_tags("<h1>This is a demo</h1>")."<br>"; // strigs out the tags from the string echo nl2br("this is a \n test"); // Inserts HTML line breaks before all newlines in a string ?> |
and thats all for this Tutorial. 🙂