Categories
PHP

Including Files in PHP – Learn PHP in 7 Days – Day #6

Include Function

Including files bring more convenience in managing your code. As the name states, include is a function that will simply dump the contents of the included file into the current file. This is cool because some times you may need some code that should be available on all pages. Say a menu or a website header.

Including files saves a lot of efforts by writing your code multiple times on each page. Yeah I know you copy and paste but that requires some more efforts too comparatively. Suppose you suddenly add a page in menu. Then? You need to update all the files. Using include function we can just create one file and include it all over in other files. Hence editing only one file will modify code in your other files.

I hope I am clear enough in explaining this to you. Let us start with an example. Oh before that, the syntax for include function is

<?php include("filename.php"); ?>

So let us first create a file called menu.php The file content would be something like this.

<a href="#">Home</a> -
<a href="#">About Us</a> -
<a href="#">Contact Us</a> <br />

Now let us create an index.php file. The index.php file will contain some content as well as the menu file. So this is what the code will be in index.php file

<html>
<head>
<title>Testing Include File</title>
<head/>
<body>
<?php include("menu.php"); ?>
<p>This page is created to display the working of include  function</p>
</body>
</html>

See the preview

7-include

Require Function

The require function is almost same as the include function. The only difference is in error handling. When the included file doesn’t exist, a warning is displayed and the execution is preceded.

Where as when a file included via require function does not exist, then a fatal error is displayed and the execution is halted at the same line. The syntax is

<?php require(“filename.php”); ?>

Related posts:

  1. MS DOS Tutorials – How to Create, Append and View Files and Move Files and Directory
  2. Handling Traffic With Custom 404 Error Pages
  3. PHP Syntax, Variables, Echo Statement – Learn PHP in 7 Days – Day #1
  4. Learn PHP in 7 Days
  5. MS DOS Tutorials – How to Create, Delete, Change, Rename Directory and Files
Categories
PHP

Using Operators in PHP – Learn PHP in 7 Days – Day #2

Operators are used for performing a variety of simple tasks like specifying values to variables, mathematical functions, comparing data etc. Although operators in PHP are categorized in 11 types, but for the sake of this crash course I will be showing you 5 tutorials. But let me list out all the 11 categories of operators.

  • Arithmetic Operators
  • Assignment Operators
  • Bitwise Operators
  • Comparison Operators
  • Error Control Operators
  • Execution Operators
  • Increment and Decrement Operators
  • Logical Operators
  • String Operators
  • Array Operators
  • Type Operators

Assignment Operator

This will be the most used operator in PHP. Function of this operator is very simple, as the name says the assignment operator is used to assign values to a variable. May it be a number, a string or another variable, or a memory address (if you remember the pointers concept in C language?)

Assignment operator is represented by equals ( = ) sign. Here are a few examples :

$myvar = 4;
$my_string_var = "abc";
$myvar2 = $myvar;
$my_address_var = & $myvar;
?>

Note that my_address_var and myvar point to same memory location thereby contain same values.

Arithmetic Operators

Arithmetic Operators are only used to perform mathematical functions like addition, subtraction etc. There are 5 arithmetic operators in PHP like any other language.

Addition (+)         Subtraction (-)            Multiplication (*)         Division (/)      Modulus (%)

Is there any scope of explanation required for the above operators? Anyways ill try it, these operators are to be put in between 2 operands. Addition is simply adding 2 numbers, similarly subtraction is for subtracting, multiplication for multiplying and division for getting the quotient.

If you don’t know what a modulus operator does, it simple returns the remainder when 2 numbers are divided. Here are a few examples however for self explanation

<?php
$add = 2 + 3;
$subtract = 7 - 2;
$multiply = 3 * 4;
$divide = 24 / 3;
$modulus = 5 % 2; ?>

echo “Perform addition: 2 + 4 = “.$add.”<br />”;
echo “Perform subtraction: 6 – 2 = “.$subtract.”<br />”;
echo “Perform multiplication:  5 * 3 = “.$multiply.”<br />”;
echo “Perform division: 15 / 3 = “.$divide.”<br />”;
echo “Perform modulus: 5 % 2 = ” . $modulus
?>

This is the output for the above piece of code

3-operators-1

Comparison Operators

Comparison operators are used to check the relationship between variables and/or values. They can only return a true or false value based on the statement that we provide. There are 6 comparison operators (up to my knowledge)

Equal (==) – to check if both the operands are equal in value
Not Equal (!=) – to check if both the operands are not equal in value
Less Than (<) – to check if first value is less than the second
Greater Than (>) – to check if first value is greater than the second
Less Than or Equal (<=) – to check if first value is less than or equal to the second
Greater Than or Equal (>=) – to check if first value is less than or equal to the second

Note that there is a huge difference between “==” and “=”. == is used to evaluate where as = is used to assign. So statement like

if ($x = 3)

Will always return true even if values of $x was not 3.

<?php
$a = 4;
$b = 4;
$c = 6;

echo $a == $b;
echo $a != $b;
echo $a < $c;
echo $a > $c;
echo $a <= $c;
echo $a >= $c;
?>

The above code will output something like this.

3-operators-2

1 represents “true” in Boolean. Yeah you already know it smart pants. So here lines 1,3,5 are true and lines 2,4,6 are false. But we don’t see any 0′s right? I know you’re smart. Echo statement cannot output Boolean false or in other terms Boolean false is nothing but a NULL value, so echo statement cannot simply output NULL values. Hence you don’t see any 0′s here.

String Operators

I think we have already seen the string operator (which I call as the dot operator) used to join multiple strings or variables. If you don’t remember I won’t mind explaining once again. You can use the string operator to join multiple strings or strings and variables like this.

$middlename = "Ameenuddin";
echo "My name is" . "Atif";
$myfullname = "Mohammed " . $middlename . " Atif";
echo "Name : " . $myfullname;

So you remember it. That’s good. Let us move on to the last type of operators now

Increment and Decrement Operators

An increment or a decrement operator can simple increment or decrement the value of any variable with 1. This can work only on integers and floating point number so forget about strings here. (Am I being rude?). Let us take an example, say we want to increment the value of $counter with 1. This is the classic way we would write

$counter = $counter + 1;

Or maybe like this too (called as shorthand)

$counter += 1;

It may look a bit absurd to write long statements for the sake of increasing a value by 1. Like most of the programming languages PHP too supports increment and decrement operators. This is however further sorted into

  • Pre Increment/Decrement
  • Post Increment/Decrement

Pre Increment/Decrement

In this way, the value of the variable is first incremented or decremented based on the operator and then returned back. A few examples for explanation

<?php
$x = 3;
$y = 7;

echo ++$x;
echo “<br />”;
echo –$y;
?>

And the output for this is

3-operators-3

So you already knew that huh! Yes the value of x is increment by 1 and printed as 4 and the value of y is decremented by 1 and printed as 6.

Post Increment/Decrement

Post Increment/Decrement works exactly opposite to pre increment/decrement. Here the variable is first returned back and then the value of the variable is incremented or decremented based on the operator. Moving forth to examples to make it simpler

<?php
$x = 3;
$y = 7;

echo “the value of x = ” . $x– . “<br/>”;
echo “The value of x is now changed to $x” . “<br/>”;;
echo “the value of y = ” . $y++ . “<br/>”;;
echo “The value of y is now changed to $y”;
?>

3-operators-4

As you can see the value of $x—or $y++ is not reflected in the first echoed text because the variable is not incremented until after the line of code is executed. However, with the pre-increment “++$x” the variable does reflect the addition immediately on the same line because it is done before returning output to the buffer.

Related posts:

  1. PHP Syntax, Variables, Echo Statement – Learn PHP in 7 Days – Day #1
  2. Learn PHP in 7 Days
  3. Sanitizing Variables in PHP without Regular Expressions
  4. MS DOS Tutorials – How to Create, Delete, Change, Rename Directory and Files
  5. MS DOS Tutorials – Learn MS DOS with an ease
Categories
PHP

PHP Syntax, Variables, Echo Statement – Learn PHP in 7 Days – Day #1

Welcome everyone to the Day # 1 of my PHP tutorials series, Learn PHP in 7 days. Today we are going to start with basic concepts of PHP like the syntax, using variables, strings and the printing output on the browser using echo statement. Without wasting your time I’ll start the tutorial right away.

PHP Syntax

Note that every statement in PHP finishes with a semicolon ” ; ” at the end except for looping structures. First I may tell you how PHP works. Working with PHP files is the same way like you work with HTML files, but these files end with a .php extension rather than .htm or .html that we usually use for HTML files.

PHP file is nothing but an HTML file. That means you can write an execute HTML inside a PHP file. That’s for sure but how on earth do we execute PHP code? That’s what we expect to learn here right?

Anything placed inside the tags (or a PHP Block) will be you PHP code. For instance:

The above statement is going to output like this on the web browser.

1-hello-world

So this is how you get your output. We execute PHP code in a PHP Block and its gets compiled and is displayed on your browser.

Example of a PHP and HTML Code

My First PHP Page
<?php echo "Hello World!";
?>

I remind you once again, every statement in PHP finishes with a semicolon ” ; ” at the end except for looping structures.

White space

White space between 2 php lines is ignored, so that means you can leave white space without any problem

Variables

A variable is something that can store changing values. If you already know any other programming language or probably Algebra, then you already know what a variable is. The concept of variables is beyond this tutorial so I assume that you already know about a variable.

Variables in PHP are stored with a dollar sign ” $ ” before the variable name. There are some naming conventions for creating variables.

PHP variables can start only with a letter or underscore “_”

PHP variables may only be comprised of alpha-numeric characters and underscores. a-z, A-Z, 0-9, or _

Examples

$myname = "Atif";
$myfullname = 'Mohd Ameenuddin Atif';
$number = 5;
$decimal = 12.25;

As the above code is pretty self explanatory, any string variable must be wrapped inside single (’) or double (“) quotes where as any integer or a floating point (decimal) number should be written straight away.

Hello World!

Let us start with a “hello world” example. Coming back to our hello world example, create a new file using your favorite text editor. Writing hefty applications in a text editor is quite hard to debug. Hence I would recommend you to get a copy of RapidPHP , that is what I use for my self.

Write the following code into the file

<?php
echo ("Hello, World!" );
?>

Now save it as lesson1.php or whatever you would like. Make sure it resides inside the www folder of your WampServer Directory. Open its relative URL like http://localhost/lesson1.php to make sure it works.

1-hello-worldAhh! Great It works!

Echo

Echo is a language construct that allows you to print any thing on the screen. The PHP command echo is a means of outputting text to the web browser. You can print any HTML using echo statement. Here are a few examples of using echo statement to output plain text

<?php I am learning PHP"; ?>
<?php HTML Title tag using PHP "; ?>

And this is how we echo a variable on the web browser.

<?php $websitename = "MyGeekPal!";
<?php echo "hi";
<?php echo "Welcome to $websitename"; ?>

This way the browser will echo the string along with the variable.

Make a note that the variable will be parsed only if its supplied within the double quotes.

An alternative of writing this would be the following way

<?php
$websitename = "MyGeekPal!";
echo "hi";
echo "<h5>Welcome to " . $websitename . "</h5>";
?>

In both the ways the output would be virtually same but when we take it in terms of CPU usage, the output will be processed faster in the second method.

The ( . ) or dot operator is used to simply join 2 expressions. The output you get is

2-echo-1How to echo quotes

To echo quotes or other extend characters like line breaks we use backslash ( ) before the character or also called as escaping text. Let us see an example

2-echo-2

Here is the output

To echo a backslash, write the backslash twice ( \ )

Heredoc method

Heredoc method is another robust method in PHP that can help you create multi line strings variables without using escape characters. Let me first write the code and then explain it to you.

$a_string = <<<TEST
MyGeekpal!
Testing PHP Heredoc
TEST;
echo $a_string;
?>

Use <<< and some identifier keyword (my suggestion would be to use some word that is no where used inside the variable.) like we used TEST.

Start writing the multi line string that you want the variable to hold from the next line onwards.

To close it, simply write the name of the identifier in the next line. Be warned that the line closing the variable must contain only the identifier that we used to start it followed by a semicolon and the line must not be indented.

This is the output that you would get

2-echo-heredoc

Related posts:

  1. Sanitizing Variables in PHP without Regular Expressions
  2. Learn PHP in 7 Days
  3. MS DOS Tutorials – How to Create, Append and View Files and Move Files and Directory
  4. How to Create a WordPress Plugin – Hello World!
  5. MS DOS Tutorials – How to Create, Delete, Change, Rename Directory and Files
Categories
PHP

Learn PHP in 7 Days

After my prolonged exams I have though to write something really productive for you all. All day long I was thinking what should be the topic that I should hit it with. At first I thought to go with HTML or CSS. But these languages are quite easier to learn. SO I though we will be going with PHP, its because I like challenges.

PHP is a great language to learn, specially for web developers. And this week through I am going to write a series of tutorials to make sure you learn the basic concepts of PHP in 7 days. Don’t afford to miss these click here to subscribe to our RSS feeds at least for the next 7 days to get your daily dose of PHP or else you can catch back on this blog everyday.

The tutorials will be starting tomorrow so once again I remind you, don’t forget to subscribe to our RSS feeds

Day #1 – PHP Syntax, Variables, Echo Statement

Day #2 – Using Operators in PHP

Day #3 – Using Comments in PHP

Day #4 – Using Conditional Statements in PHP

Day #5 – Using Loops in PHP

Day #6 –Including Files in PHP

Related posts:

  1. MS DOS Tutorials – Learn MS DOS with an ease
  2. Google Updates PageRank – Google Loves Me !
  3. Welcome to MyGeekPal
  4. How to automatically tweet your blog post
  5. MS DOS Tutorials – How to change colors in DOS prompt