PHP Tutorial – a Beginner’s Basic PHP Guide Part 1

arp14 PHP, Tutorial Tags: , , , , , 1

Hi, this PHP tutorial is created for beginners. In this PHP tutorial, we will learn how, PHP works, PHP short tags vs normal tags, syntax, variables, flow control and looping, functions, single and multidimensional arrays and more…

PHP is a very powerful server side scripting language designed for Web development to produce dynamic stunning web pages overnight. PHP is to be embedded into an HTML source document. PHP is installed on more than 20 million Web sites and 1 million Web servers. PHP is easy to learn. more about PHP on Wikipedia…

If you’re a PHP beginner, you’ll enjoy this PHP tutorial! So, let’s start learning php!

Basic information about PHP

PHP code is embedded in to HTML source document. Extension of PHP files are .php

Mime type of PHP eis “application/x-httpd-php“.

Install PHP on Local machine

Requirements

  1. PHP (http://php.net/downloads.php)
  2. Apache Web Server (http://httpd.apache.org/)
  3. MySQL (If you need database – http://dev.mysql.com/downloads/)

To make installation and configuration process short, there are few click installation packages available out there. You can download and install those all-in-one packages from below.

How PHP works?

Working struture (work flow) of php

Hello World!

To print something on a web page, we can use ‘echo’ or ‘print’ command. In most cases, echo will be faster than print! I’ll be using ‘echo’ rest of this PHP tutorial. So open a PHP file with your favorite text editor and write the codes as below. Make sure PHP is installed on your server. Remember, if you are on your local computer, open the file from localhost otherwise from your server.

<?php
	echo "Hello World!"; // output: Hello World!
?>

Get server information and configurations

Use the code below to get complete server information and configurations:

<?php phpinfo(); ?>

Scripting Basics

PHP Short Tags Vs. Normal Tags

There are two kind of tag syntax available in PHP. To use short tags, It must be enabled in php.ini configuration file as ‘short_open_tag = On’. Short tags are good at when we need to echo things out on as short space as possible. Syntax are below:

<?=$variable?> or, <?="a string like this"?> // short tags
<?php // normal tags
	echo $variable;
	echo "a string like this";
?>

See more about it here – PHP Short Open Tags & Short Hand Syntax Cheatsheet

Basic Language Syntax of PHP

<?php
# This is a comment.
// This is also a comment.
/* This is a set of comments.
This block of multi-line comments can span as many lines as needed.
Be sure you open and close the block with the forward-slash and asterisk. */
$value = 2000.1234;
$name = "Arpan Das";
$x = 10; $y = 20; $z = $x + $y;
$result = ((10 + 20) * 5) / (y +1);
$i++;
$i--;
$i = $i + 1;
$i = $i -1;
$str = "Hello"." "."World!";
$fname = "Brad";
$lname = "Miller";
$name = $fname." ".$lname;
if ($x > 10) {
	echo "The value is big enough!<BR>because $x > 10";
}
// Valid constant names
define ( "MAX" ,   1000 );
define ( "MIN" ,   3 );
define ( "SERVERNAME" , "www.w3epic.com" )
?>

Declaring and Assigning Variables in PHP

<?php
$age = 21; // integer
$price = 14.50; // float
$isReady = TRUE; // boolean
$name = "Arpan Das"; // string
$fname = "Arpan"; // string
$lname = "Das"; // string
$name = $fname + " " + $lname; // extended string
$day = "Tuesday"; // string - value is Tuesday
$var = "day"; // string - value is day
$$var = "Friday"; // string  - value of $day was Tuesday, now it is Friday
echo $$var; // printing variable variable - output Friday
echo $day; // printing variable - output Friday
unset($age); // unset value of variable $age
//note that a FALSE value doesn't display a value!!
?>

isset(), empty() and unset()

<?php
	$foo = "PHP Tutorial is so cool!";
	$int = 14;
	$bool = true;

	if(isset($foo)) echo "foo is set <br />"; else echo "foo is not set <br />";
	if(isset($int)) echo "int is set <br />"; else echo "int is not set <br />";
	if(isset($bool)) echo "bool is set <br />"; else echo "bool is not set <br />";
	if(isset($bar)) echo "bar is not set <br />"; else echo "bar is not set <br />";

	if(empty($foo)) echo "foo empty <br />"; else echo "foo is not empty <br />";
	if(empty($int)) echo "int empty <br />"; else echo "int is not empty <br />";
	if(empty($bool)) echo "bool empty <br />"; else echo "foo is not empty <br />";
	if(empty($bar)) echo "bar is empty"; else echo "bar is not empty <br />";

	// unset their values
	unset($foo); unset($int); unset($bool);
?>

NULL, is_null()

<?php
	$foo = NULL; // it is null but it is set!
	$bar = "hello world!"; // it is not null and set

	if (is_null($foo)) echo "foo is null <br />";
	if (is_null($bar)) echo "bar is not null <br />";

	if (isset($foo)) echo "foo is set <br />";
	if (isset($bar)) echo "bar is also set <br />";

	unset($foo);
	if (isset($foo)) echo "foo is not set";
?>

Flow control and Looping in PHP

If-else Statement and switch statement

<?php
/* We'll be using logical operators && (and), || (or), ! (not)
(Comparison Operators: ==, !=, <>, <, >, >=, <=)
if, else, elseif returns boolean TRUE or FALSE */

	$a = 5; $b = 10;

	if ($a > $b) {
		echo "a is greater than b <br />";
		echo "b is less than a <br />";
		// multiple line continue doing stuffs
	} elseif ($a == $b) {
		echo "a and b are equals <br />";
		// multiple line continue doing stuffs
	} else {
		echo "a is less than b <br />";
		echo "b is greater than a <br />";
		// multiple line continue doing stuffs
	}
// or, with short single line if else syntax
	if ($a > $b) echo "a is greater than b <br />";
	elseif ($a == $b) echo "a and b are equals <br />";
	else echo "a is less than b <br />";

// switching val with if else statement
	$val = 10;
	if($val == 5) echo "val is 5 <br />";
	elseif ($val == 10) echo "val is 10 <br />";
	elseif ($val == 15) echo "val is 15 <br />";
	else echo "val is unknown <br />";

// doing same with switch statement
	switch ($val) {
		case 5:
			echo "val is 5 <br />";
			break;
		case 10:
			echo "val is 10 <br />";
			break;
		case 15:
			echo "val is 15 <br />";
			break;
		default:
			echo "val is unknown <br />";
	}
// NOTE: break; will preventing to jump to next case when the case is matched.
?>

For loop, While loop and Do-while loop

<?php
// the for loop
	for ($i=0; $i<10; $i++) { 
		// the loop starts with i's value 0, i has limit of 10, i increasing by adding 1to itself each times.
		echo "<p id='para{$i}'>This is paragraph no <b>{$i}</b>.</p>";
		// this will continue 10 times.
		// each time =, it's value will be 1+ its current value
		// this loop get stopped automatically when i'll be less than 10
		// you can loop HTML elements, play with classes, nest elements etc...
	}

// the while loop
	$value = 1;
	while ($value <= 5) { // continue loop until value is less tha equal to 5
   	echo $value, ", "; // printing values chained by comma
   	$value++; // looping each times, value increase by adding 1 to itself
	}

// the do-while loop - does same as regular while loop
	$value = 1;
	do {
   	echo $value, ", ";
   	$value++;
	} while ($value <= 5);
?>

Break and Continue

<?php
	for ($i=1; $i<=10; $i++) {
		echo "<p style='background-color: #{$i}{$i}{$i};border:{$i}px solid #f00; color: #fff;'>i is {$i}.</p>";
       if ($i == 7) break; // "break" - breaks the loop on certain condition matched
		// otherwise the loop continues until until the limit condition matched
   }
?>

Infinite Loop

<?php
	$limit = 5;
	for ($i=1; $i<=$limit; $i++) {
		echo "<p style='background-color: #{$i}{$i}{$i};border:{$i}px solid #f00; color: #fff;'>i is {$i}.</p>";
		$limit++; // the second condition also increases looping each times, this ways it never ends!
		// beware of it; I'm adding a break after i reaches 50. It eats resource and CPU time.
		if ($i==50) break; // comment this line out to test.
   }
?>

Working with Arrays in PHP

Creating and using array

<?php
	$arr = array(1, 52, 12, 254, 111, 0, 712); // arr is an array with 7 keys and 7 values.
	echo $arr[0].'<br />'; // output: 1 // keys are starts from 0, 1st element = 0th key, 2nd = 1st.
	echo $arr[1].'<br />'; // output: 52

	$months = array(1=>'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec');
	echo "5th month is " . $months[5] . "<br />"; // but here, key manually starts from 1

	print_r($months); // to print entire array with key value format, use print_r(), useful for debugging. 

	// changing array values
	$arr[1] = 100;
	echo $arr[1]; // changed from 52 to 100.

	// assigning keys by strings
	$alph = array("a" => "apple", "b" => "ball", "c" => "cat", "d" => "dog");
	print_r($alph);

	$unsorted = array(43, 22, 17, 1, 10 => 14,  5 => 12, 77, 17 => 56);
	print_r($unsorted); // on a unsorted array, where it breaks continuing, 
	// it catches to the next from where it stopped at last. try the code and see.
?>

You can use count() or sizeof() to get size of an array and loop through. To remove a element from an array, use unset(). Some of the array sorting functions are sort, rsort, arsort, ksort, unsort, and more on php.net!

Looping Arrays

<?php
	$arr1 = array( 100 , 217 , 333 , 212 , 11 , 44, 17, 89, 109 );

	foreach($arr1 as $arr) echo "value: {$arr} <br />"; // this is called foreach loop

// or,

	reset($arr1);
	$value = current ($arr1);
	echo "the current array value is: $value.<br>";
	$value = next ($arr1);
	echo "the next array value is: $value.<br>";
	$value = next ($arr1);
	echo "the next array value is: $value.<br>";
	echo "the current key is: ", key($arr1), ".<br>";
	echo "now resetting the array.<br>";
	reset($arr1);
	echo "the current key is: ", key($arr1), ".<br>";
	echo "going to the end of the array.<br>";
	end($arr1);
	echo "the current key is: ", key($arr1), ".<br>";
?>

There are many built-in arrays that you can work with. ($_SERVER, $_ENV, $GLOBALS, $ _POST, $ _GET, $ _COOKIE, $ _SESSION, $_REQUEST)

Multidimensional Arrays

<?php
	// 1d array
	$arr_1d[0] = "zero";
	$arr_1d[1] = "one";
	$arr_1d[2] = "two";

	// 2d array
	$arr_2d[0][0] = "zero zero";
	$arr_2d[0][1] = "zero one";
	$arr_2d[0][2] = "zero two";

	$arr_2d[1][0] = "one zero";
	$arr_2d[1][1] = "one one";
	$arr_2d[1][2] = "one two";

	// 3d array (don't worry! You don't need a 3g glass - LoL :))
	$arr_3d[0][0][0] = "zero zero zero";
	$arr_3d[0][0][1] = "zero zero one";
	$arr_3d[0][0][2] = "zero zero two";

	$arr_3d[0][1][0] = "zero zero zero";
	$arr_3d[0][1][1] = "zero one on";
	$arr_3d[0][1][2] = "zero one two";
	// Its crazy ... and continues...
?>

You will hardly need a 3d array to work with. The dimension increase, complexity increase.

Array Functions

array_flip(), array_reverse(), shuffle(), and more on php.net!

Check the next part of this tutorial for more on PHP- PHP Tutorial – a Beginner’s Basic PHP Guide Part 2

One thought on “PHP Tutorial – a Beginner’s Basic PHP Guide Part 1

Leave a Reply

Note: Your email address will not be published. Required fields are marked *