PHP for Beginners – Part 3

by  
Share:
PHP for Beginners

Hey Guys! In this part of the tutorial you will be learning how to create functions, play with single and multidimensional arrays and string related functions.

This is the most crucial part of the tutorial series. Almost every time things which you will learn in this section are used in practical life when you code. So please give your full effort.

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/sibling to wake you up early in the morning. As being requested 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.

  // general syntax 
  function <function name >(optional_argument, another_optional_argument) {
    statements;
    statement;
    optional return value;
  }

Have a look at the example below.
<?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.
<?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 used in more than section, then code it as 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.

<?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 dimensional array or array of arrays.

<?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

<?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 index. Look at the example below you will get to know what I am talking about.

<?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

<?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
?>

This brings us to the end of this tutorial.

I am once again asking you to focus more in this section as this is the most crucial aspect of the tutorial.

Get the latest updates directly in your inbox for FREE: Subscribe here

Share your feedback / let me know your doubts regarding this tutorial in the comment box given below.

Share:
Hasan

Shahrukh Khan (Hasan)

A software engineer who's a die-hard coder, blogger, dreamer and mentor with years of expertise in web development. Know more...

Related Posts

Vikash Kumar on

The reference functions really helped. Very nicely explained too. Great job.

Reply
Parshv Shah on

very nice blog..
Each n every things r decribed perfectly..
Perfect job done by u!!!
I though php will take more time to learn..but this series of 5 tutorial helped me a lot…
i learned this series within a weekk..n this is only because of this guy…
thnk u very much…

Reply
kowsalya on

I am kowsalya .I want to learn Php but this download option is not work .pls help me

Reply
Shahrukh Khan on

double click on the social link it will work.

Reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.