Wednesday, January 31, 2018

PHP Array tutorials with example


One of the most useful data structures supported by PHP is arrays. An array is a collection of data elements that are of the same type. For instance, if you wish to store 20 integers, then it can be stored in an array of 20 elements. You can also look at arrays as a collection of variables of the same type; each of which is capable of storing data.

PHP supports three types of arrays, which include  :- 

•   numeric arrays, 
•   multi-dimensional arrays  
•   associative arrays. 

The individual elements of the array can be accessed using the index or position of the element in the array. The three types of arrays differ in the manner their elements are accessed. Numeric arrays have numeric index that are incremented in a linear fashion. For instance, the first element of the array has the default index of 0. For all elements succeeding this data value, the index is incremented by 1.

            On the other hand, associative arrays have strings as index. The array is composed in a key-value fashion and the keys are stored as index while the values are accessed using the keys. Therefore, the storage of elements and their accessibility is dependent upon the association between the key and value.

Lastly, an array can be composed of elements each of which is an array in itself. Such an array is 2-dimensional. Correspondingly, the dimensionality of an array can be increased depending on the programming requirement. Arrays that have multiple dimensions are called multi-dimensional arrays. Moreover, the elements of such arrays are accessed using multiple indices.

◆   Numeric Array 

Numeric arrays can store any type of data like strings, numbers and objects. However, the only thing worth remembering is that the array’s indices are numeric. Moreover, the default index of the first element of the array is zero. The function used to create arrays is array(). Sample code to demonstrate the functionality of numeric arrays is given below for your reference.

◆   Associative Arrays 

Associative arrays are similar to numeric arrays in the way they function. However, their indexing mechanism is different. They work on the key-value format. Values have keys, which are The associative arrays are very similar to numeric arrays in term of functionality but they are different in terms of their index. Associative array will have their index as string so that you can establish a strong association between key and values.

For instance, if you need a data structure to store the salaries of employees, then the same can best be done using an associative array. In this case, employee names can be used as keys and salaries as values. Please note that you must never put associative arrays inside double quotes as they don’t return any value in that case. Sample code to demonstrate the functioning of associative arrays is given below –




/*Creating associative array using method 1*/ 

$salary = array('james' => 20000, 'jacob' => 15000, 'maria' => 7500); echo "Salary of first employee is ". 

$salary['james'] . "<br />"; echo "Salary of second employee is ". 

$salary['jacob']. "<br />"; echo "Salary of third employee is ".  

$salary['maria']. "<br />"; 

/*Creating associative array using method 2*/ 

$salary['james'] = "high"; 

$salary['jacob'] = "medium"; $salary['maria'] = "low"; 

echo "Salary of first employee is ". $salary['james'] . "<br />"; 

echo "Salary of second employee is ". $salary['jacob']. "<br />"; 

echo "Salary of third employee is ". $salary['maria']. "<br />"; 




◆   Multi-dimensional

Arrays In a multi-dimensional array, every element of the array is also an array. Therefore, a multi-dimensional array is composed arrays, which in turn can also be made up of arrays. In order to access elements of a multi-dimensional array, multiple indices must be used. Sample code to demonstrate the functioning of multi-dimensional arrays is given below –

Monday, January 29, 2018

Decision Making in PHP

Making Decisions

Like most programming languages, PHP lets you write code that can make decisions based on the result of an expression. This allows you to do things like test if a variable matches a particular value, or if a string of text is of a certain length. In essence, if you can create a test in the form of an expression that evaluates to either true or false, you can use that test to make decisions in your code.

You studied expressions, but you might like to quickly review the “Operators and Expressions”section in that chapter to give yourself an idea of the kinds of expressions you can create. You can see that, thanks to the wide range of operators available in PHP, you can construct some pretty complex expressions. This means that you can use almost any test as the basis for decision-making in your code.

PHP gives you a number of statements that you can use to make decisions:

•  The if statement
•  The else and elseif statements
•  The switch statement

You explore each of these statements in the coming sections.

◆  Simple Decisions with the if Statement

The easiest decision-making statement to understand is the if statement. The basic form of an if construct is as follows:

if ( expression )

// Run this code

// More code here

If the expression inside the parentheses evaluates to true, the code between the braces is run. If the expression evaluates to false, the code between the braces is skipped. That’s really all there is to it.

        It’s worth pointing out that any code following the closing brace is always run, regardless of the result of the test. So in the preceding example, if expression evaluates to true, both the Run this code and More code here lines are executed; if expression evaluates to false, Run this code is skipped but More code here is still run.

Here’s a simple real-world example:

$widgets = 23; 

if ( $widgets == 23 )

echo "We have exactly 23 widgets in stock!";


The first line of the script creates a variable, $widgets, and sets its value to 23. Then an if statement uses the == operator to check if the value stored in $widgets does indeed equal 23. If it does —and it should! —the expression evaluates to true and the script displays the message: “We have exactly 23 widgets in stock!”If $widgets doesn’t hold the value 23, the code between the parentheses —that is, the echo() statement —is skipped. (You can test this for yourself by changing the value in the first line of code and re-running the example.)

 Here’s another example that uses the >= (greater than or equal) and <= (less than or equal) comparison operators, as well as the && (and) logical operator:

$widgets = 23; 

if ( $widgets >= 10 && $widgets <= 20 )

echo "We have between 10 and 20 widgets in stock.";


This example is similar to the previous one, but the test expression inside the parentheses is slightly more complex. If the value stored in $widgets is greater than or equal to 10, and it’s also less than or equal to 20, the expression evaluates to true and the message “We have between 10 and 20 widgets in stock.”is displayed. If either of the comparison operations evaluates to false, the overall expression also evaluates to false, the echo() statement is skipped, and nothing is displayed.

The key point to remember is that, no matter how complex your test expression is, if the whole expression evaluates to true the code inside the braces is run; otherwise the code inside the braces is skipped and execution continues with the first line of code after the closing brace. You can have as many lines of code between the braces as you like, and the code can do anything, such as display something in the browser, call a function, or even exit the script. In fact, here’s the previous example rewritten to use an if statement inside another if statement:

The code block between the braces of the first if statement is itself another if statement. The first if statement runs its code block if $widgets >= 10, whereas the inner if statement runs its code block —the echo() statement —if $widgets <= 20. Because both if expressions need to evaluate to true for the echo() statement to run, the end result is the same as the previous example.

If you only have one line of code between the braces you can, in fact, omit the braces altogether:

$widgets = 23;

if ( $widgets == 23 ) 

echo "We have exactly 23 widgets in stock!";

However, if you do this, take care to add braces if you later add additional lines of code to the code block. Otherwise, your code will not run as expected!

◆   Providing an Alternative Choice with the else Statement :- 

As you’ve seen, the if statement allows you to run a block of code if an expression evaluates to true. If the expression evaluates to false, the code is skipped.

You can enhance this decision-making process by adding an else statement to an if construction. This lets you run one block of code if an expression is true, and a different block of code if the expression is false.


if ( $widgets >= 10 )


echo "We have plenty of widgets in stock."; } else


 echo "Less than 10 widgets left. Time to order some more!";


If $widgets is greater than or equal to 10, the first code block is run, and the message “We have plenty of widgets in stock.”is displayed. However, if $widgets is less than 10, the second code block is run, and the visitor sees the message: “Less than 10 widgets left. Time to order some more!”

You can even combine the else statement with another if statement to make as many alternative choices as you like:

◆   The switch statements :- 

The switch statement is a very useful programming construct in scenarios where a single variable is to be tested for different values. The same programming scenario can be implemented using nested if statements. However, the switch is a more efficient option for this as it creates a table of values and according to the value received, the execution directly jumps to the code block corresponding to that value.The syntax for using the switch statement is as follows –

switch (expression){ case value1: -

Code block if the expression evaluates to a value equal to value1;


case value2: -

Code block if the expression evaluates to a value equal to value2; break;


Code block if the expression evaluates to a value that is not equal to value1 or value2;       }

Sample code that implements this concept has been given below for your reference. Read More

Friday, January 26, 2018

PHP comparison operators

Basic operators

Any computer language uses operators to calculate or compare variables, most of which are self explanatory.


PHP uses + (plus),
 - (minus), 
* (multiplication), 
/ (division), 
%( modulo) and "=" the assignment operator.

Let's discuss the modulo operator. The modulo operator is used in finding the resultant remainder after one number has been divided into another. The following are a couple of examples to help you better understand:

The first example is 15 % 5 = 0. As you can see, 5 divides evenly into 15 with no remainder, so the result we get is 0. Now let's use 10 % 7 = 3 as our second example. Because 7 divides into 10 once and leaves a remainder of 3, our answer must be 3.

30 % 6 = 0 (30 - 5 * 6 = 30 30 - 30 = 0)
30 % 7 = 2 (30 - 4 * 7 = 30 - 28 = 2)
30 % 8 = 6 (30 - 3 * 8 = 30 - 24 = 6)

Comparison operators

◆.   $ a = = $ b Equal TRUE if $ a is equal to $ b after type adjustment.

◆.    $ a = = = $ b Identical TRUE if $ a is equal to $ b, and they are of the same type.

◆.   $ a != $ b Not equal TRUE if $ a is not equal to $ b after type adjustment.

◆.  $ a < > $ b Not equal TRUE if $ a is not equal to $ b after type adjustment.

◆.  $ a != = $ b Not identical TRUE if $ a is not equal to $ b, or they are not of the same type.

◆.   $ a < $ b Less than TRUE if $ a is strictly less than $ b.

◆.  $ a > $ b Greater than TRUE if $ a is strictly greater than $ b.

◆.    $ a < = $ b Less than or equal to TRUE if $ a is less than or equal to $ b.

◆.    $ a > = $ b Greater than or equal to TRUE if $ a is greater than or equal to $ b.

Let's see an example with = = = identical operator :-


a = b

a and b are not identical

$ a and $ b are equal because they equal 10, but they are not identical because $ a is a string and $ b is an integer.

$ a = 9; Assignment: $ a equals 9.

$ a + = 7; Addition-assignment: $ a equals $ a plus 7.

$ a *= 4; Multiplication-assignment: $ a equals $ a multiplied by 4.

$ a /= 3; Division-assignment: $ a equals $ a divided by 3.

$ a .= 6; Concatenation-assignment: $ a equals $ a concatenated with 6

Let's write a simple code converting Fahrenheit to Celsius:-

Output: -

F = 80

C = 26.6666666667

Please pay attention to "F =". $ F." < br >" on the code line echo; Here we concatenate 3 separate strings into one.

"F ="

$ F

"< br >" –HTML break.

Two dots are placed between our three strings because dots are used to concatenate strings in

PHP: "F =" $ F "< br >";

The fact is that $ F is not a string. It is an integer because it is equal to 80. If $ F were equal to "80" it would be a string.

When we concatenate the $ F variable between 2 strings, because PHP converts it to a string, there is no need to do anything further.

As I wrote earlier, a string of text can be enclosed in single quotation marks:

echo 'F ='. $ F.' < br >';

To output a string of text, you can use the "print" command instead of the "echo" command.

However, in this case, you would use parentheses and single or double quotation marks.

Print(' F ='. $ F.' < br />');


print(" F =". $ F." < br />");

PHP variables are case sensitive, so $ F is not the same as $ f, and $ lastname is not the same as $ Lastname or $ LASTNAME.

Let us say that we wish to use PHP to output a web page to a browser using the following HTML link:

< a href =" http://" > yahoo </ a >

If we write Print(" < a href =" http://" > yanhoo </ a >");

We would receive an error message due to the use of double quotation marks in our HTML code. To avoid the error message, use single quotation marks for the print command as I've done in the following:-

print(' < a href =" http://" > yanhoo </ a >');

The same is true for an HTML input element:

echo '< input type =" text" name =" lname" value =" James"/ >';


print(' < input type =" text" name =" fname" value =" John"/ >');

One handy feature of PHP code is the ability to include one file inside another. The creation of a website solely in HTML requires you to edit every single page of that website if you later wish to change the navigation, logo or footer. The use of PHP to create the web pages allows you to include one file with navigation or logo in every web page requiring you to edit only one file to later change the navigation or logo.

There are two commands to include the file in your PHP code:

Include(' top_menu.php');


Required(" footer.php");

The difference between the two is, when using the "include" command, if the file to be included does not exist, you will be given a warning message; however, the execution of the rest of the PHP code will not be interrupted. Conversely, when using the "required" command, if the required file is not found, a fatal error message is displayed and the execution of the PHP code will cease.Read More 

Thursday, January 25, 2018

Types of Inheritance in PHP


Recall Mindi’s tattoos, specifically the tattoo on her back? The tattoo on her back was described as protected in PHP terms meaning that it was visible within the Mindi class and to classes that extended the Mindi class. To inherit in PHP5, you should use the keyword extends in the class definition.

Class parent


Class child extends parent



Inheritance passes "knowledge" down. It is a structured way of extending code and functionality into new programs and packages. Classes are created in hierarchies and inheritance allows the structure and methods in one class to be passed down the hierarchy. That means less programming is required when adding functions to complex systems. If a step is added at the bottom of a hierarchy, then only the processing and data associated with that unique step needs to be added. Everything else about that step is inherited. The ability to reuse existing objects is considered a major advantage of object oriented programming.

◆.    Method Overriding 

Method overriding is when the function of base class is re-defined with the same name, function signature and access modifier (either public or protected) of the derived class.

The reason to override a method is to provide additional functionality over and above what has been defined in the base class. Imagine that you have a class by the name of Beverage from which you derive two child classes, Martini and Scotch. The Beverage class has methods defined to stir, mix, etc, but each of the specialized classes Martini and Scotch will have its own style of mixing and stirring and hence would need to override the stir and mix functionality.

Lets look at an example with Beverage:

◆.   Invoking Parent Methods 

First of all, “invoke” means to call, to request the action of something. I just wanted to get that brief explanation out of the way. Now, when you override a method of the base class, its functionality is completely hidden unless it has been explicitly invoked from the child class. To invoke a parent class method you should use the keyword parent followed by the scope resolution operator “:: “ followed by the name of the method as mentioned below:

Parent : : function_name();

Look at the example below: 

In the above example, look at the way in which the showData() function in the Employee child class is invoking the Person parent class’s showData() function. When the program executes the showData() method if the Employee class is called which in turn calls the showData() function of the parent class. After the parent class’s showData() function completes its execution the remaining code in showData() function of the Employee class is executed.

◆.   Horizontal Inheritance – Using Traits 

PHP does not support multiple inheritance; a class can only extend a single base class. What happens if you need code from more than one class? Until recently, developers had to accomplish this in a crude manner by copying and pasting code from additional classes that was needed outside of its base class. Now this can be done by way of a new feature introduced in PHP5.4 called a trait that provides a means of horizontal inheritance.

A trait looks like a class in the way it is structured but it cannot be instantiated. Properties and methods can be defined within a trait structure but they can only be used by a class that incorporates them with the use keyword which is called within the class that uses it, that is, it goes inside the curly braces. It isn’t called in the class definition outside the curly braces like interfaces and the extending class.

◆.    Encapsulation

Encapsulation means what the term implies, to put in a “capsule,” to place functionality into a single package. Consider an object as a capsule or a box that has things in it. The access modifiers are like windows that control who gets to see inside with ‘public’ access being a wide open window that let's everyone see inside and ‘private’ access being fully shaded that doesn't let anyone see inside.

The control over the visibility of the contents of an object is a big part of how encapsulation works. The contents of an object are properties and methods and because they are all packaged inside an object they make up a sort of mini-program that has control over how visible its contents, data, are. This is encapsulation.

Technically speaking, encapsulation refers to the creation of self-contained modules that bind processing functions to the data. Encapsulation ensures good code modularity, which keeps routines separate and less prone to conflict with each other. To reiterate, you can think of each object as a mini program that handles it’s own responsibilities as it’s own self contained capsule or pill.

◆.    Polymorphism

Now that you know that a class is a blueprint and that an object is constructed based on that class it is important to understand that many different objects can be created from the same class. I may have a single class for a table but I can create many different kinds of table objects from that class.

I could have a round table, a square table, a long table a short table. I could have a blue table or a brown table. I could have a table made of oak or one made from plastic; all from the same base class.

Polymorphism simply means many forms. In computer programming, polymorphism is the ability to create a variable, a function, or an object that has more than one form in order to provide capability of adapting to what needs to be done. It is a mechanism by which objects of different types can process data through a single interface. Polymorphism is used to make applications more modular and extensible. Instead of messy, hard to read conditional statements describing different courses of action, you create interchangeable objects that you select based on what you need. That is the fundamental goal of polymorphism.

Polymorphism is a mechanism by which objects of different types can process data through a single interface. Using a typical illustrative example, a program might define a type of object called Animal, containing a function called speak() and, through inheritance, derive object sub-types such as Cow, Dog, etc. that each have their own specific implementation of the speak() function. The mechanism of polymorphism allows such a program to call the speak() function without actually knowing whether it is calling it for a Cow, Dog, or any other derivative Animal, while executing the correct function for the specific type of Animal.

Polymorphism is not the same as method overloading or method overriding (in OOP, a method is a function that belongs to a class, while the class variables are referred to as its members) and should not be confused with these. Read More

Wednesday, January 24, 2018

PHP Look-ahead and Look-behind

Lookahead and Lookbehind 

In patterns it’s sometimes useful to be able to say “match here if this is next.” This is particularly common when you are splitting a string. The regular expression describes the separator, which is not returned. You can use lookahead to make sure (without matching it, thus preventing it from being returned) that there’s more data after the separator. Similarly, lookbehind checks the preceding text.

Lookahead and lookbehind come in two forms: positive and negative . A positive lookahead or lookbehind says “the next/preceding text must be like this.” A negative lookahead or lookbehind indicates “the next/preceding text must not be like this.” Table  shows the four constructs you can use in Perl-compatible patterns. None of the constructs captures text.

Table - Lookahead and lookbehind assertions

Construct                                Meaning

(?= subpattern )             Positive lookahead 

(?! subpattern )              Negative lookahead 

(?<= subpattern )            Positive lookbehind 

(?<! subpattern )           Negative lookbehind 

A simple use of positive lookahead is splitting a Unix mbox mail file into individual messages. The word "From" starting a line by itself indicates the start of a new message, so you can split the mailbox into messages by specifying the separator as the point where the next text is "From" at the start of a line:

$messages = preg_split ( '/(?=^From )/m' , $mailbox ); 

A simple use of negative lookbehind is to extract quoted strings that contain quoted delimiters. For instance, here’s how to extract a single-quoted string0 (note that the regular expression is commented using the x modifier):

The only tricky part is that to get a pattern that looks behind to see if the last character was a backslash, we need to escape the backslash to prevent the regular expression engine from seeing \) , which would mean a literal close parenthesis. In other words, we have to backslash that backslash: \\) . But PHP’s string-quoting rules say that \\ produces a literal single backslash, so we end up requiring four backslashes to get one through the regular expression! This is why regular expressions have a reputation for being hard to read.

Perl limits lookbehind to constant-width expressions. That is, the expressions cannot contain quantifiers, and if you use alternation, all the choices must be the same length. The Perl-compatible regular expression engine also forbids quantifiers in lookbehind, but does permit alternatives of different lengths.Read More

Tuesday, January 23, 2018

Changing & Casting Type PHP

Changing by casting 

You can also cause a variable’s value to be treated as a specific type using a technique known as type casting. This involves placing the name of the desired data type in parentheses before the variable’s name. Note that the variable itself remains unaffected; this is in contrast to settype(), which changes the variable’s type.

In the following example, a variable’s value is cast to various different types at the time that the value is displayed:

Note that $test_var’s type isn’t changed at any point; it remains a floating-point variable, containing the value 8.23, at all times. All that changes is the type of the data that’s passed to the echo statement.

Here’s the full list of casts that you can use in PHP:-

Function                                     Description

(int) value or (integer) value  Returns value                                                   cast to an integer

(float) value                             Returns value           
                                                   cast to a float

(string) value                            Returns value                                                      cast to a string

(bool) value or (boolean) value   Returns                                                                  value cast                                                            to a Boolean

(array) value                              Returns value                                                      cast to an array

(object) value                            Returns value                                                    cast to an object

You can also cast a value to an integer, floating-point, or string value using three PHP functions:

Function                                 Description

intval( value )                          Returns value                                                     cast to an integer

floatval( value )                        Returns value                                                          cast to a float

strval( value )                            Returns value                                                        cast to a string

By the way, intval() has another use: converting from a non–base-10 integer to a base-10 integer. To use this feature, pass intval() a string representation of the non–base-10 integer, followed by the base of the integer. For example, intval( "11", 5 ) returns a value of 6 (the base-5 number 11 converted to a decimal number).

Why would you want to change a variable’s type with settype(), or change a value’s type with casting? Most of the time, PHP’s loose typing handles type conversion for you automatically, depending on the context in which you use variables and values. However, forcing a variable to be of a certain type is useful for security reasons; if you’re expecting to pass a user-entered integer value to a database, it’s a good idea to cast the value to an integer, just to make sure the user really did enter an integer. Likewise, if you’re passing data to another program, and that program expects the data to be in string format, you can cast the value to a string before you pass it.

                  Essentially, use explicit casting or settype() whenever you want to be absolutely sure that a variable contains data of a certain type. Read More

Saturday, January 20, 2018

PHP string manipulate

Introducing String LANGUAGE

Introducing Strings Now that you’ve been introduced to the general concept of variables, let’s look at variables in detail. The first variable type to delve into is the string. A string is merely a quoted chunk of characters: letters, numbers, spaces, punctuation, and so forth. These are all strings:

•“In watermelon sugar”
•‘August 2, 2011’

      To make a string variable, assign a string value to a valid variable name:

$ first_name = 'Tobias'; 

$ today = 'August 2, 2011'; 

When creating strings, you can use either single or double quotation marks to encapsulate the characters, just as you would when printing text. Likewise, you must use the same type of quotation mark for the beginning and the end of the string. If that same mark appears within the string, it must be escaped:

$ var = "Define \" platitude\", please."; 

Or you can also use the other quotation mark type:

$ var = 'Define "platitude", please.'; 

To print out the value of a string, use either echo or print:

echo $ first_name;

To print the value of string within a context, you must use double quotation marks:

echo "Hello, $ first_name"; 

You’ve already worked with strings once—when using the predefined variables in the preceding section (the values of those variables happened to be strings). In this next example, you’ll create and use your own strings.

Script 1.     String variables are created and their values are sent to the Web browser in this script.

To use strings

1. Begin a new PHP document in your text editor or IDE, to be named strings.php, starting with the initial HTML and including the opening PHP tag (Script 1.):

<! DOCTYPE html PUBLIC "-// W3C// DTD XHTML 1.0 

Transitional// EN" 
"http:// www.w3. org/ TR/ xhtml1/ DTD/ xhtml1-transitional.dtd" > 
< html 
xmlns =" http:// www.w3. org/ 1999/ 
xhtml" xml:lang =" en" lang =" en" > 
< head > 
< meta http-equiv =" Content-Type" content =" text/ html; 
charset = utf-8" /> 
< title > Strings </ title > 
</ head > 
< body >
 <? php # Script 1. - strings.php 


Within the PHP tags, create three variables:

$ first_name = 'Haruki'; 
$ last_name = 'Murakami'; 
$ book = 'Kafka on the Shore'; 

This rudimentary example creates $ first_name, $ last_name, and $ book variables that will then be printed out in a message.

3. Add an echo statement:

echo "< p > The book
< em > $ book</ em > was written by 
$ first_name $ last_name. </ p >"; 

All this script does is print a statement of authorship based upon three established variables. A little HTML formatting (the emphasis on the blog’s title) is thrown in to make it more attractive. Remember to use double quotation marks here for the variable values to be printed out appropriately (more on the importance of double quotation marks at the blog end).

Complete the PHP block and the HTML page:

?> </ body > </ html > 

Save the file as strings.php, place it in your Web directory, and test it in your Web browser . The resulting Web page is based upon printing out the values of three variables.

If desired, change the values of the three variables, save the file, and run the script again .

The output of the script is changed by altering the variables in it.


If you assign another value to an existing variable (say $ book), the new value will overwrite the old one. For example: $ book= 'High Fidelity'; $ book = 'The Corrections'; /* $ book now has a value of 'The Corrections'. */


 PHP has no set limits on how big a string can be. It’s theoretically possible that you’ll be limited by the resources of the server, but it’s doubtful that you’ll ever encounter such a problem.

Script 1. Concatenation gives you the ability to append more characters onto a string.

1.   <! DOCTYPE html PUBLIC "-// W3C// DTD XHTML 1.0 Transitional// EN" "http:// www.w3. org/ TR/ xhtml1/ DTD/ xhtml1-transitional.dtd" > 

2.     < html xmlns =" http:// www.w3. org/ 1999/ xhtml" xml:lang =" en" lang =" en" > 

3.     < head > 

4.       < meta http-equiv =" Content-Type" content =" text/ html; charset = utf-8" /> 

5.    < title > Concatenation </ title >

 6.      </ head > 

7.      < body > 

8.   <? php # Script 1. - concat.php 

10.   // Create the variables: 

11.    $ first_name = 'Melissa'; 

12.   $ last_name = 'Bank'; 

13.   $ author = $ first_name . ' ' . $ last_name; 


15.    $ book= 'The Girls\' Guide to Hunting and Fishing'; 


17.    // Print the values: 

18.      echo "< p > The blog< em > $ bloggers</ em > was written by $ author. </ p >"; 


20.        ?> 

21.     </ body > 

22.      </ html >

Read More 

Thursday, January 18, 2018

Why will need PHP

Why will need PHP 

The most important requirement for working with PHP—because it’s a server-side scripting language—is access to a PHP-enabled server. Considering PHP’s popularity, your web host most likely has this option available to you on their servers. You’ll need to contact them to see what technology they support.

  Your other option is to install PHP and a web server application (like Apache) on your own computer. Users of Windows, Mac OS X, or Linux can easily install and use PHP for no cost. Directions for installing PHP are available in Appendix A, “Installation and Configuration.”If you’re up to the task of using your own PHP-installed server, you can take some consolation in knowing that PHP is available for free from the PHP website

( and comes in easy-to-install packages. If you take this approach, and I recommend that you do, then your computer will act as both the client and the server.

The second requirement is almost a given: You must have a text editor on your computer - Atom, Notepad + +, UltraEdit, and similar freeware applications are all sufficient for your purposes, and TextMate, SublimeText, and other commercial applications offer more features that you may appreciate. If you’re accustomed to using a graphical interface (also referred to as WYSIWYG—What You See Is What You Get) such as Adobe Dreamweaver or Aptana Studio, you can consult that application’s manual to see how to program within it.

The popular Dreamweaver application supports PHP development, among other server-side technologies. 

Third, you need a method of getting the scripts you write to the server. If you’ve installed PHP on your own computer, you can save the scripts to the appropriate directory. However, if you’re using a remote server with a web host, you’ll need an SFTP (Secure File Transfer Protocol) program to send the script to the server. There are plenty of SFTP applications available; for example, in  “Getting Started with PHP,”I use the free FileZilla (http:// )

The FileZilla application can be used on many different operating systems to move PHP scripts and other files to a remote server.

Finally, if you want to follow the examples in  “Intro to Databases,”you need access to MySQL ( ). MySQL is available in a free version that you can install on your own computer.

MySQL’s website (as of this showing).

This blog assumes only a basic knowledge of HTML, although the more comfortable you are handling raw HTML code without the aid of a WYSIWYG application such as Dreamweaver, the easier the transition to using PHP will be. Every programmer will eventually turn to an HTML reference at some time or other, regardless of how much you know, so I encourage you to keep a good HTML blog by your side. One such introduction to HTML is Elizabeth Castro and Bruce Hyslop’s HTML, XHTML, and CSS: Visual QuickStart Guide (Peachpit Press, 2014). Previous programming experience is certainly not required. Read More

Wednesday, January 17, 2018

Why learn PHP

Why learne PHP

The important reasons to learn PHP as  first server side programming language:-

●   PHP is an open source language. This means that all PHP modules are available freely and can be customized to fit the requirements of any application.

● There are lots of free hosting services available that only support PHP; other server side languages, such as ASP.NET, have high costs associated withhosting.

●  Being the first advanced server side language, PHP has a huge developer’s community where you can seek help if face issues.

●  The installation and deployment of PHP based websites is a matter of few simple clicks.

●  PHP supports procedural as well as object oriented programming in PHP4 and PHP5.

●  PHP have several famous frameworks that can be used as the foundation for building your web applications. Some of them include WordPress, Joomla, Cake PHP, Drupal, and Symfony.

Installing the Local Server Your PHP

based web pages are going to run on a live web hosting server; however, for development and testing purposes, it is always advisable to use a local webserver. Fortunately, everything you need to install in order to run your PHP pages on local servers come packaged in a single installation known as XAMP (Operating System, Apache, MySQL and PHP). The last three characters remain constant while the operating system is a variable denoted by X. If you are using a Linux based system, you can use LAMP. Similarly, you can use a WAMP installation package for Windows-based systems. Depending on the system you have, you can download the corresponding installation package from the following link:

https:// download.html

Note: For this book, we are using the WAMP server. Please note that PHP script and programming syntax remains the same in different operating systems. Even if you are developing on a system other than Windows, you can follow along.
       When you go to the above link, you will find options to download XAMP for different operating systems. You can choose XAMP for Windows from that page. You can download it from following link as well:

http:// en

Installation Steps:

To download and install WAMP servers on your machine, follow these steps:

1.  When you click on the above link, a page will appear. The second menu item in the menu bar is the download option; click that. You will see two download options, one for 32 bit and one for 64 bit. This is shown in the following figure:

2.   Once you select the OS from 32 or 64 bit, warning messages will be displayed in a pop up box. If you look at the second line, you will see the link “download directly”at the end of the second line. Click it. (Refer to figure for reference)

3.  Depending on the browser (or the downloader manager) you are using, you will be presented with a download option. Download the file.

4.    Now, go the directory where you downloaded the file and open it. You should see the WAMP server installation wizard. Click the “Next”button.

5.   You will be presented with the license agreement window. Check the accept agreement radio button and click .

6.  A new window will appear that will ask for the installation path. I recommend leaving the default path as it is and clicking the “Next”button.

7.  On the window that appears, check both boxes and click “Next”.

8.  A dialogue box will appear. Click the “Install”button to start the installation process. During installation, the option to select the default browser will appear. Select the default browser for your web page (you can change it later). At the end of the installation, you will be presented with a window to enter the SMPT and Email servers. Leave both the fields filled with default values and click .

9.  On the dialogue box that appears, click the “Finish”button. (Leave the only box checked). See the below figure for reference: Testing the Local Server Once you have installed the local server following the aforementioned steps, you will see a green WAMP icon at the bottom right of your system tray. This is shown in the following figure:

Testing the Local Server 

Once you have installed the local server following the aforementioned steps, you will see a green WAMP icon at the bottom right of your system tray. This is shown in the following figure:

Click the icon. A panel should appear at the bottom right of the system, as shown in the following figure:

If you click the top option, “Localhost”, you should see a webpage appear in your default browser. If your WAMP server is running successfully without any issues, you should see following page in the browser:

The last thing I want you to check before we end this blog is the “www”directory. This is the directory where we will place our PHP files. In order to open this directory, again go to the WAMP panel and click the “www directory”option. This is the fourth option from the top.

Once you click the “www directory”option, your “www”directory Will be opened in a new window. Your “www”directory should contain following this :-


And that’s it for the blog In this blog, we learned how to install the WAMP server. In the blog we will run  first PHP program and the process of PHP please clicking the Link above mentioned and learn how to run first Programming process in PHP.  READ MORE

Tuesday, January 16, 2018

PHP Identifier


An identifier is simply a name. In PHP, identifiers are used to name variables, functions, constants, and classes. The first character of an identifier must be an ASCII (American Standard Code for lnformation Interchange) letter (uppercase or lowercase), the underscore character ( _ ), or any of the characters between ASCII 0x7F and ASCII 0xFF. After the initial character, these characters and the digits 0–9 are valid.

Monetize your website traffic with yX Media

Some Identifier name are :-
●    Functions
●    Constant
●    Variable
●    Classes

Variable names :- 

Variable names always begin with a dollar sign ( $ ) and are case-sensitive. Here are some valid variable

Here are some illegal variable names:

$not valid



These variables are all different due to case sensitivity:-





Function names:-

Function names are not case-sensitive (functions are discussed in more detail in Chapter 3). Here are some valid function names:-

These function names refer to the same function:-

howdy     HoWdY       HOWDY      HOWdy howdy

Class names :-

Class names follow the standard rules for PHP identifiers and are also not case-sensitive. Here are some valid class names:



The class name stdClass is reserved.


A constant is an identifier for a simple value; only scalar values—Boolean, integer, double, and string can be constants. Once set, the value of a constant cannot change. Constants are referred to by their identifiers and are set using the define() function:- READ MORE

define('PUBLISHER',           "O'Reilly &



Monday, January 15, 2018

PHP Class Constructor

PHP Class Constructor

Let us first see a simple piece of code:-

 We  can learn my post OOP  (please Click this URL)  OOP ( object oriented Programming)  We just try to take that knowledge a bit further and add some juice into it.

We are imagining about a “Car class”. We want to make several new cars from it with different features. Next we’ll try to discuss about the advantages and limitations of using these new car objects.

Monetize your website traffic with yX Media

Let us see the code first: -

Class of PHP
Class of PHP code 

Run it either on your browser or on the terminal. Get this output:

string( 3) "RED" 

bool( false) 

It says the new car object “suzuki”is of red color. Then we ask, “Is it bought?”The default value is ‘false’so it comes out as “bool( false)”. Let us create another car object “maruti”and let it call the “buy()”method.

Look at the code:-

public function buy() { 

$ this-> is_bought = TRUE; 

The “buy()”method makes the property “is_bought”–TRUE :-

 $ maruti = new Car(" Blue"); 

var_dump( $ maruti); 

$ maruti-> buy(); 

var_dump( $ maruti-> is_bought); 

So when we create another car object “maruti”we get this output :-

object( Car)# 2 (2) {

 [" color"] = > 

string( 4) "Blue" 

[" is_bought"] = > 

bool( false) 

bool( true) 

You see the code now becomes more meaningful and close to the reality. It’s not that everybody goes to the car showroom to buy a car. For that reason we have kept the “is_bought”property “false”. When the consumer buys a car it sets to “TRUE”.

This scenario changes when two developers from two different parts of the world work on the same “Car class”. Suppose they both name their file “car.PHP”. A name collision is inevitable. What you can do to avoid such unpleasant situation? The answer is “Namespace"


Well, the name suggests it, as I have just said. It’s a great thing for developers as it is a great relief for them. They don't have to write unnecessary long name of methods to avoid name collisions.

As you know, 'foo.txt' can’t appear in the same directory. You have to place them in a separate directory like
            ‘/ home/ ss/ folderone’and
‘/ home/ ss/ foldetwo’and finally when you call ‘foo.txt’from a certain folder, you need to mention the whole path. Using the directory separator you can only reach ‘/ home/ ss/ folderone/ foo.txt’and the same rule is applicable for the other folders also.

   In PHP world, 'namespace' serves the same purpose. It, primarily, avoids name collision encapsulating items and applications can write the reusable codes without worrying about the name collisions. Now they can write short classes and functions.

            Before we go through an example there is one important thing to remember. In PHP 5 or higher version through namespace only classes (abstract classes and traits), interfaces, functions and constants are affected. READ MORE 


 <? php namespace 

MyProject\ sub\ level; 

const CONNECT_OK = 1; 

class Connection { ... }

 function connect() {....} 



 Declaring multiple namespaces in a single file is permissible but not desirable. In PHP 7, we’ll see later, how this problem has been solved.

Sunday, January 14, 2018

OOP's Concept in PHP

OPP (object oriented Programming

 OOP (object oriented Programming), The uninitiated PHP developers would never try to make their hands dirty and feet wet with code and will depend on them forever. 

So the first step is start believing in your potentials, powers and strength of your mind. Coding is like writing. I show you how easy it is! - The Best Popunder Adnetwork

Consider a piece of writing where you’re trying to describe a robot. So in your writing ‘robot’is the subject. In object oriented programming the ‘robot’is the object. In a piece of writing, your subject ‘robot’has some descriptions like –the robot has three eyes, two noses, six arms. 

                  In OOP we need to write a class ‘Robot’which has those properties are mentions in a image :- 

OOP PHP code 

When you run this script, the output is as expected: The robot has 3 eyes, 2 noses, 6 arms.

 All we have done is very simple –we wrote a Robot class where we have defined properties and methods. Next, we have created a robot object and through which we have put some life into it. The robot has jumped into life and says it has 3 eyes, 2 noses and 6 arms. 

Is it okay? Apparently, it’s definitely okay. But, there could be some problems. Suppose somebody changes the last line of code:-

 $ robot-> showRobot( 3, two, 6); 

Look, instead of passing an integer the user passes a string. Well, php will tackle it by its own way. It’ll give you an output like this: The robot has 3 eyes, two noses, 6 arms. 

But, we intended to give an integer, isn’t it? In PHP 7 this problem has been solved. The scalar type declaration has made it mandatory to pass integer when integer value has been asked for. 

 write a our old code this way :-  

// Code/ php7book1/ index.php 

<? php 

class Robot { 

public $ eye; 

public $ nose; 

public $ arm; 

public function showRobot( int 

$ eyes, int $ noses, int $ arms) { 

$ this-> arm = $ arms; 

$ this-> eye = $ eyes; 

$ this-> nose = $ noses; 

echo "The robot has {$ eyes} eyes, 

{$ noses} noses, {$ arms} arms";


// class ended 

$ robot = new Robot(); 

$ robot-> showRobot( 3, 2, 6); 

The change has taken place only on this line: -

public function showRobot( int $ eyes, int $ noses, int $ arms) 

Here we have mentioned, categorically, that the parameters should be passed as integers. Now, if anybody passes string or any thing other than integer it’ll throw errors. Read More