Intro to PHP Programming

What can I do with PHP?

PHP is a server-side scripting language. The client will always see and interact with HTML in his browser. PHP is capable of generating dynamic HTML pages and hence it can output HTML which servers as a presentation layer and in the backend, on the server it can continue to process all requests made by the client. These requests could be processing of form, handling cookies, uploading files, generating dynamic HTML by querying a database etc.

PHP can also be used from command line to execute php scripts. This is similar to running a UNIX shell or a perl script from command to accomplish tasks like taking backup of files, analyzing log files, generating a list of files and folders etc.

PHP is capable of doing much more than what read above. You can use it on command line interface to do most of the tasks stated above, without a browser, of course. PHP can also be used to create rich GUI applications using PHP-GTK kit. This requires knowledge of advanced PHP features.

Let's look at some of the popular features of PHP.

Popoular Features of PHP

Some of the most popular features of PHP are as mentioned below:-

  1. PHP works on multiple Operating Systems. Some are Linux, manu Unix flavors, BSD, Mac OS X and many more..

  2. Plenty of Web Servers are supported. Some are Apache, IIS, Netscape iPlanet and many others..

  3. Use it as a procedural programming or object oriented programming. Choice is yours!

  4. Dynamic generation of HTML, PDF, Flash, Text, CSV, XML and others..

  5. Support for numerous databases like MySQL, Oracle, MS-SQL, Sybase, PostgreSQL and many others..

  6. Interaction with services like LDAP, POP3, SMTP etc..

  7. Extensive online documentation

  8. Huge amount of built in functions to make most tasks easier.


Basics of PHP

You must understand and remember few things about creating PHP files. And these are:-

  1. Every PHP file will have an extension of .php or optionally .php3 You have an option to change these default file extensions using the web server's configuration file(s).

  2. A .php file should have all the PHP code inside <? (opening tag) and ?> (closing tag). The opening tag can be <?php as well. It will then be treated as php language code and parsed accordingly. This is useful when you want to mix PHP code with HTML.

  3. PHP can be embedded inside HTML, but in a slightly different fashion. In between the HTML tags where ever you want to make use of PHP code, you will have to use <? php code ?> and this will be parsed by PHP.

  4. All statements must end with a ;(semicolon). This is very important and this semicolon tells the PHP parser to treat this line as a single statement. Without this you will see error messages when parsing the code.

Your first PHP code

Why not display some output onto the screen? It is in fact much easier to accomplish with PHP. All you have to do is use PHP language construct called echo and we are done. Here's how.

Open a blank new file in your editor or notepad and write the below mentioned lines in the file. Then save the file with a .php extension. If you are using notepad as editor then be careful about the file extension. In Windows OS the file extensions are often hidden, so you must ensure that file saved has a .php extension. Ok, take a look at the code below..

<? echo "This is my first line!"?>
 Or, you can write it using other declaration tag as well, which is
<?php echo "This is my first line!"php?>

This is my first line!

If that is the exact output on your browser, then it is a success!!!

Case Sensitivity

All the keywords and built-in constructs are case in-sensitive. Which means, there is no difference between echo and ECHO

Handling Statements

All statements are separated using a semicolon. It's only a compound statement such as if loop or a conditional loop which does not need a semicolon before and after the closing bracket. For example:

<?php
if (a=b) {
echo "a and b are equal"  // Semicolon is not needed here
}                     // Semicolon is not needed here
?>

Commenting the code

Code require commenting for a many reasons. The commented code is not parsed by PHP and is a good way of adding comments about statements, code and functions. All lines starting with // will be treated as a comment by PHP. One can also using # to comment the code. Example:

<?php
// Function to echo string passed as an argument
function echo_string($a) {
echo $a   // The value of variable a will be printed on screen
}
?>

Now you know that the text in first line and third line after // are treated as comments.

Variables in PHP

Variables

A variable is something that is subject to variation or likely to vary. In PHP variables are represented with a dollar sign before the variable name. For example $a, $b are variables. The variable name is case-sensitive and must always start with a character. So, $a and $A are different variable names. Some examples are:

<?php
$first_name 'firstname'//Valid
$last_name 'lastname'//Valid
$Middle_Name 'middlename'//Valid
echo "$firstname, $Middle_Name, $last_name";
$9Name 'name';  //not valid. Variable name can not start with a number
?>

Predefined variables

PHP provides significant number of predefined variables, some of which are platform dependent, version specific, server specific.

Some of the widely used predefined variables are:

Server variables:

$_SERVER when used, offers information such as hostname, script name, location etc. When used, the information is obtained onto this array from the web server running PHP. However, as we read before, you may not be able to get all the information when this variable is used.

Widely used elements of $_SERVER are as mentioned below:

'PHP_SELF' refers to file name of the currently executed script. For instance if the URL is http://www.phpcatayst.com/examples/self.php then $_SERVER['PHP_SELF'] will refer to /examples/self.php

'argv' array of arguments passed to the script.

contains the number of command line parameters passed to the script

'SERVER_ADDR' the IP address of the server on which the current script is executing.

'SERVER_NAME' the hostname of the server on which the current script is executing.

'REQUEST_METHOD' request method which was used to access the page; i.e. 'GET', 'HEAD', 'POST', 'PUT'.

'QUERY_STRING' the query string, via which the page was accessed.

'DOCUMENT_ROOT' the document root directory under which the current script is executing. This information is obtained from server's configuration file.

'HTTP_ACCEPT' contents of the Accept: header from the current request, if there is one.

'HTTP_REFERER' the address of the page which referred to the current page.

'HTTPS' set to a non-empty value if the script was queried through the HTTPS protocol.

'REMOTE_ADDR' the IP address from which the user is viewing the current page.

'REQUEST_URI' the URI used to access the current page.


Data Types in PHP

In PHP a variable can hold data of any type. These data types are as following:

  • Integer - An integer is a non-fractional, whole number such as 1, 2, 3, 4, 88, 1000, 1374747. The range of integer is operating system specific.

  • Real Number - It is also known as a floating number or floating point number. It is not a whole number and has fractions such as 1.22, 2.45, 100.765 etc.

  • String - Also called character string, it consists of a series of characters such as "php".

  • Boolean - A boolean is a true or a false value.

Assigning data types

Unlike other programming languages, PHP does not require formal declaration of the data type of a variable. When you assign certain value to a variable, PHP will automatically try to guess the type of data being stored and assign the data type to the variable. When needed PHP will automatically convert the data type.

<?
$a 5//Storing an integer
$b 5.5 //Storing a floating number
$c $a $b// $a is integer and $b is floating number
?>

Here data type of $a is automatically converted to a real number and then added with the value of $b which is a real number too.

Type Casting

Sometimes, there might be a need to change the data type of a certain variable from string to an integer and then back to a string. Such manual over riding of data types is called Type Casting. Since PHP will automatically change the data type, chances are rare that you will need to use type casting at all. To specify a different of a particular data type, use the following:

<?
$a = (int) $b;  //changing to a variable
$a = (string) $b;  //changing to a string
$a = (float) $b;  //changing to a real number
?>

Determining Data Type

To find out the data type of a variable, use a statement like the following:

<?
$a 100// storing an integer
var_dump($a);
//This prints the value stored in the variable $a ?>

This will output the data type and value of the variable. In this case, the output will be int(100)


Expressions and Operators

Expressions

PHP can also be called an expression-oriented language that is because everything you write in PHP is an expression. An earlier example where we've assigned 100 to $a, an integer value of 100 or either a string 100 is being stored in the variable $a. You may also assign a string "hello" to $a by writing $a = hello; Now, if you were to write $b = $a, then $b is containing the string "hello".

Using PHP it is also possible to assign a function to a variable by writing $a = function_a(); and this is all possible because PHP is an expression-oriented language as well. Another good example of expression orientation is pre- and post-increment and decrement. This is achieved using variable++ and variable--. These are known as increment and decrement operators. For example: if you want to increment $a by 1, you can simply write '$a++' or '++$a'. But if you want to add more than 1 to $a, say 4, then you will have to write '$a++' or '++$a' multiple times. A better practice is to write '$a = $a + 4'. '$a + 4' evaluates to the value of $a plus 4, and is assigned back into $a, which results in incrementing $a by 4. This can also be written as '$a += 3' which executes faster than previous ways of incrementing values. Extending this, any two-place operator can be used in this operator-assignment mode, for example '$a -= 10' (subtract 10 from the value of $a), '$b *= 5' (multiply the value of $b by 5), etc.

A very common type of expressions are comparison expressions. These expressions evaluate to either FALSE or TRUE. PHP supports > (bigger than), >= (bigger than or equal to), == (equal), != (not equal), < (smaller than) and <= (smaller than or equal to). The language also supports a set of strict equivalence operators: === (equal to and same type) and !== (not equal to or not same type). These expressions are most commonly used inside conditional execution, such as if statements.

Operators

An operator is something that you feed with one or more values which yields another value. There are three types of operators.

  • Unary operator - which operates on only one value

  • Binary operators

  • Ternary operator: ?: - used to select between two expressions depending on a third one

Arithmetic Operators

It's like basic arithmetic. You add, multiply, subtract, divide.

<?
//Example Code for Arithmetic Operators
-$a// Negation
$a $b//Addition - This adds values of $a and $b
$a $b// Subtraction - Difference of $a and $b
$a $b// Multiplication - Product of $a and $b
$a $b// Division - Quotient of $a and $b - returns a float value anytime
$a $b// Modulus - Remainder of $a divided by $b
?>

Assignment Operators

The basic assignment operator is "=" which means that the left operand gets set to the value of the expression on the right.

<?
//Example Code
$a 10//sets value of $a to 10 
$b $a//sets value of $b to the value of $a 
echo $b//you will see output as 10 
$a = ($b 20) + 10// $a is equal to 30 now, and $b has been set to 20 
?> 

Comparison Operators

One of the most important operators are Comparison Operators. They help you compare two values. Take a look at this table:

Example

Name

Result

$a == $b

Equal

TRUE if $a is equal to $b.

$a === $b

Identical

TRUE if $a is equal to $b, and they are of the same type. (introduced in PHP 4)

$a != $b

Not equal

TRUE if $a is not equal to $b.

$a <> $b

Not equal

TRUE if $a is not equal to $b.

$a !== $b

Not identical

TRUE if $a is not equal to $b, or they are not of the same type. (introduced in PHP 4)

$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.

Remember, when comparing an integer with a string, the string is converted to a number. If you compare two numerical strings, they are compared as integers.


Control Structures in PHP


Flow-Control Statements (Control Structures)

As you get deeper into programming, you will see a need of executing a series of statements based on conditions. Based on your requirement, statements can be grouped into a statement-group by encapsulating a group of statements with curly braces like { and }.

if construct


if (expr)
    statement

If the expression evaluates to TRUE, PHP will execute statement, and if it evaluates to FALSE - it'll ignore it.

Let us look at a simple logical flow before we attempt to write PHP code for the same. In fact, when I started to learn programming, I first started to write simple english statements and then wrote coding for them. So, here it is:

Step1 - I want to check if value of $a is bigger than 5
Step2 - If value of $a is bigger than 5, I want to print "Bigger than 5" on screen. Else if value is not bigger than 5, I want to do nothing.
Step3 - End of my logic

Now, writing the same code, programmatically:

<?php
$a 6;
if ($a 5) {
   echo "Bigger than 5";
   }
?>

In the above code, the expression is evaluated to either TRUE or FALSE and in this case, if value of $a is found to be bigger than 5, it evaluates to TRUE and then the statements within the statement-group are then executed. In this example, we have already assigned a value of 6 to $a, but you should try to assign values less than 5 and test the results. As we said earlier, you can group more statememts in the statement-group and execute them. Try the example and check the result:

<?php
$a 6;
if ($a 5) {
   echo "I evaluated the value of a";
   echo "and found it to be";
   echo "bigger than 5";
   }
?>

You could also do the following:

<?php
$a 6;
if ($a 5) {
   echo "Bigger than 5";
   $b $a;
   }   
?>

Now, if you were to execute the above code, it will print the string "Bigger than 5" and then assign the value of $a to $b. Have some fun with this code, try this:

<?php
$a 6;
$b 10;
if ($a 5) {
   echo "Bigger than 5";
   $b $a;
   }
echo $b;
?>

Here, if $a is bigger than 5, value of $a is assigned to $b and the same is printed on screen. Change the value of $a in first line to 4 and see what happens?

I hope, you had a good learning session with if construct. If you need more examples in this section, please contact us and let us know.

You now know how to execute statement(s) if certain condition is met. In this section we will execute a statement in case the expression in the if statement evaluates to FALSE. Let's start with looking with the example that we had used earlier:

<?php
$a 6;
$b 10;
if ($a $b) {
   echo "a IS bigger than b";
   } else {
   echo "a is NOT bigger than b"
   }
?>

In the above example, swap the values of $a and $b and then check the results. I hope, you are understanding the use of else construct. Often, we want to execute statement, when the expression in if statement is evaluated to TRUE. But, in case, we want to execute a different set of statement when the expression is evaluated to FALSE and that's when else plays a role. Remember that else statements are executed ONLY when the expression in if statement is evaluated to FALSE. There is another construct called 'elseif' which is a combination of if and else. Unlike else, it will execute that alternative expression only if the elseif conditional expression evaluates to TRUE. See this example elseif statement for better understanding:

<?php
$a 1;
$b 2;
if ($a $b) {
   echo "a is bigger than b";
} elseif ($a == $b) {
   echo "a is equal to b";
} else {
   echo "a is smaller than b";
}
?>

In this example, the if construct evaluates if $a is bigger than $b. If TRUE, it will execute the statement within the curly brackets which is "a is bigger than b". If found to be FALSE, it will move onto elseif construct which will then evaluate the condition to check if values of $a and $b are equal (note the use of ==, Comparison Operators) and if found TRUE will execute the statement "a is equal to b". If FALSE, it will move onto the else construct which does not evaluate any condition but will execute the statement "a is smaller than b" because the condition of if previous expression was evaluated to be false. Try changing the values of $a and $b to understand this better.

while statement

Using while statement is very simple. Let's first look at the basic syntax/form of while statement:

while (expr)
   statement

In while statement, group of statement(s) are executed as long as the expression in while statement evaluates to TRUE. The condition and its evaluation is checked at the beginning of each iteration. A simpler example of while statement would be:

Step1 - Assign value of 1 to $i
Step2 - Print the value of $i and increment it by 1 till the value of $i becomes 10

Writing it using while statement would look something like:

<?php
$i 1;
while ($i <= 10) { //Execute the statements below if this is TRUE
   echo $i//Print the value of $i
   echo " "//print a space
   $i++;  //Increment value of $i by 1
   }
?>

do-while loop

Let us start with the syntax of do-while loops:

do {
   statement
} while (expr);

The only difference between a while and do-while statement is that expression is evaluated at the end of each iteration instead of doing it at the beginning. In a do-while loop, the statement will run the first time and when it reaches end of statements the expression is evaluated. Based on the exression being TRUE or FASLE, this iteration is either repeated or ends.
See this example of do-while loop:

<?php
$i 1;
do {
   echo $i;
   echo " "//print a space
   $i++;
} while ($i >= 10);
?>

In the example, it first prints the value of $i, then increments it by 1 and then evaluates the expression in while statement. Try changing the value of $i from 1 to 10 and see what happens?

for loops

for loops are more complex in strcuture than other loop strutures in PHP. The general syntax for a for loop is:

for (expr1; expr2; expr3)
   statement

Here, the first expression (expr1) is executed without any conditions at the very beginning of the loop. Then at the beginning of each iteration, the second expression (expr2) is evaluated and if found to be TRUE, the nested statements are executed. This is one iteration cycle. If the expression (expr2) is evaluated to be false, the execution of the loop ends there. And, at the end of each iteration, the third expression (expr3) is executed.



In this example, the first expression is '$i=1' which is executed without any conditions. Now the iteration begins, and at the beginning of the iteration, the second expression $i less than or equal to 10 is evaluated. Since it evaluates to FALSE ($i is 1 and is smaller than 10), the statement 'echo $i' is executed and then the last expression '$i++' is executed thus incrementing the value of $i by 1. Now, we are inside the loop, and second expression is evaluated, is found false, prints the value of $i and increments by 1. This iteration continues till the second expression evaluates to be TRUE which is value $i being equal to 10.

foreach construct

PHP provides us with an easy way to iterate over arrays. Since we have not convered arrays so far, we will skip this construct here for now. You may however visit the PHP documentation site to read about foreach construct.

switch statement

One of the most easiest statement is switch statement. It matches the value of the variable in context and if the value matches, it then executes certain code depending on what you want it to execute. All switch statements evaluate every case with a comparision operator '=='. This might cause some probelm with comparing string to integers. Let's understand switch statement with an example:

<?php
switch ($input) {
case "a":
   echo "input is a";
   break;
case "b":
   echo "input is b";
   break;
case "c":
   echo "input is c";
   break;
   }
?>

Switch statements are not good only for strings but also holds equally good for numbers. See this example:

<?php
switch ($input) {
case 0:
   echo "input is 0";
   break;
case 1:
   echo "input is 1";
   break;
case 2:
   echo "input is 2";
   break;
   }
?>

switch statements can also be empty, like this:

<?php
switch ($input) {
case 0:  //This is empty
case 1:
   echo "input is 1";
   break;
case 2:
   echo "input is 2";
   break;
   }
?>

When a case is not found, you may find it easier to handle with 'default':

<?php
switch ($input) {
case 0:
   echo "input is 0";
   break;
case 1:
   echo "input is 1";
   break;
case 2:
   echo "input is 2";
   break;
default:
   echo "input is not 0, 1 or 2";   
   }
?>


Functions in PHP

A function will let you create a logic grouping of code to perform one or more related or different tasks. This helps a programmer in many ways. Using functions, you may avoid writing repetitive code in your programs, change the logic at one place and it reflects at every place where the function is used. Let us begin by taking a look at this example:

Our requirement is to print numbers from 1 to 10 and it is how basic coding would look like:

<?php
echo "1";
echo "2";
echo "3";
echo "4";
echo "5";
echo "6";
echo "7";
echo "8";
echo "9";
echo "10";
?>

Yes, it was easy to write 10 lines of 'echo' and obtain the output. But what if you were asked to write code to print 1 to 1000 or even more? I see that you are now thinking about steps to accomplish this task. Don't worry, this is what functions are used for! When you write a function, it will become easy to just pass the starting and ending number and the list will be automatically printed.
A simple function to print all numbers between two numbers may look like this:

<?php
function print_numbers($start_num, $end_num) {
for ($i=$start_num,$i<=$end_num,$i++) {
echo $i;
}
}
?>

Now, if you were to call this function to print values between 10 and 100, all you will have to do is this:

print_numbers(10, 100) // This will print numbers between 10 and 100

The values which are being passed to function (in our example $start_num and $end_num) are called parameters or arguments. You may specify many number of parameters based on your requirements. The same function can be used to print a range of numbers such as:

print_numbers(10, 100)
print_numbers(25, 100)
print_numbers(20, 40)

Going forward, if you want to print a list of numbers between two numbers, all you have to do is call the function and pass the starting and ending numbers (as parameters/arguments). The code inside the function will do the rest.

Let us now look at declaring a function in PHP and learn more about it.

Let's begin with the general syntax/form of a function:

<?php
function functionname($arg1$arg2, .., $argN) {
    statements;
    }
?>

Some rules about function names are that a valid function name will always begin with a letter or an underscore and may follow with any number of letters or numbers. You should try to use a function name which is most relevant to what it is meant to do. For example, if your function will calculate difference between two given numbers, then a function name of "diff_numbers" is more appropriate than "my_function". Isn't it? But you are free to use whatever name you want to assign to your functions as long as it helps.

You can use functions in variety of ways. Some other ways of using functions are as mentioned below:

Calling a function inside another function:
It's very much posssible in PHP to call a function inside another function as is the case with other programming languages. A simple example will look like this:

<?php
function parent() 
  {
    function child() 
    {
      statements;
    }
  }

parent(); //calling the function called parent

child(); //calling the function called child
?>

You must have notices that a function which was inside another function was called from outside. That is possible because in PHP all functions are global functions and can be called from outside the function as well.

Calling a function based on conditions:
You can call a condition based on control statetement's evaluations. An example is:

<?php
$a 5;
$b 5;

function print_true()
      {
      echo "A and B are equal";
      return;
      }
      
function print_false() {
      echo "A and B are not equal";
      }

if ($a == $b) {
      print_true(); //calling the function
      
      else {
      print_false(); //calling the function
      }
?>

In the above example the condition is evaluated first and if found true then a call to function print_true() is made, else if the condition evaluates to false, a call to the function print_false() is made.

Now, we will learn to pass arguments to a function in PHP. It is much simpler than what you think. Here is a basic example to begin with:

<?php

function print_input($input) {
      echo "$input";
      } 

print_input(5);

?>

In the above example, we first declared a function called print_input() and an argument of $input. When you want to pass a value to that argument, all you have to do is call that function and pass a value into it as we did by calling it print_input(5). The arguments are comma separated values, so if you want to use more arguments for the same function, it will look somewhat like this:

<?php

function print_input($input,$input_a) {
      echo $input;
      echo "<br>"//Printing a blank line
      echo $input_a;
      } 

print_input(5,6); //passing an argument of 5 and 6 to the function

?>

In the above example, notice that we have added one more argument to the function, $input_a. This allows us to pass two arguments to the function when we call it, such as - print_input(5,6). You can increase the number of arguments to the argument's list and use it accordingly.


Scope of a Variable

By default, most variables in PHP will have only single scope. This single scope is available to the included files as well. For example

<?php
$a 10;
$b 20;
$c 30;
include 'cal.php';
?>

In the above example, the variables $a, $b, $c will be available within the included file cal.php as well. But this differs for the variables used inside a function. Let's see this example:

<?php 
$a 10;
$b 20;
$c 30;

function print_sum() {
    $d $a+$b+$c;
    echo $d;
  }
print_sum(); //calling the function  
?>

Upon execution of the above code, you will see 'Undefined Variable' notices. This is because, when you use $a, $b and $c variables within the function, they are treated as local variables and hence the value of which is not obtained from the variables used outside of the function. To be able to use these variables, you will have to declare them as global variables inside the function using the global keyword. See the modified example:

<?php 
$a 10;
$b 20;
$c 30;

function print_sum() {
    global $a$b$c ;  //Declaring the variables as global variables
    $d $a+$b+$c;
    echo $d;
  }
print_sum(); //calling the function  
?>

Now execute the code and you will see an output. This is because after declaring the variables as global, the variables which are declared outside the function becomes available within the function as well. Note that in our example, the variable $d is still a local variable within the function print_sum().

We hope that the above explanation was clear.


Built-in Functions in PHP

Like any other programming language, PHP offers several built-in function for day-to-day use in your coding. Most of these functions are very helpful in achieving your programming goals and are well documented.

Some (not even most) usage of built-in functions are as mentioned below:

  • Converting a string of letters to uppercase and lowercase

  • Displaying and using the date and time

  • Initializing and closing a database connection

  • Declaring and using an array

  • Handling files

  • Accessing data in forms

  • Filesystem Functions

  • Function to open FTP connections

  • Email related functions

  • Mathematical Functions

  • MySQL specific functions

  • URL Functions

  • Image functions

Handling Strings in PHP

Strings in PHP

In programming world, a sequence of characters enclosed together is called a string. Ideally, a string is enclosed in double quotes("") such as "String". String can also be enclosed in single quotes('') such as 'hello' but it behaves and functions in an entirely different fashion. See this example to understand this:

In the examples below I have used '\n', for your HTML out put replace that with <br> HTML tag for output in a new line.

<?php 
$a "hello";
$b 'hello';

echo $a;
echo "<br>"//Printing a new line
echo $b;
?>

The output of the above code will look like

hello
hello

Here we assigned a string hello to $a and also $b. While assigning this to $a we used double quotes and in case of $b we used single quotes. How does it matter? See the example with slight modification:

<?php 
$a "hello\n"//attempting multi-line output
$b 'hello\n'//attempting multi-line output

echo $a;
echo "<br>"//Printing a new line
echo $b;
?>

The output of the above code will look like

hello
hello\n

You will notice that '\n' was not printed in the output of variable $a, but it is visible in output of the variable $b. That is because when double quotes are used, the special characters used in the strings such as '\n' (linefeed) or a '\r' (carriage return) or a '\t' (horizontal tab) are processed by the PHP compiler but when using a single quote, this does not happen. When double quotes are used, PHP will process escape sequence for special characters. We will see one more example to expand our understanding of single and double quotes.

Note: Use <br> HTML tag in for output in HTML pages and use '\n' in Text and Email for new lines.

<?php 
$drink "Tea";
$drink_1 "Coffee";

echo "My first preference is for $drink<BR>";
echo 'My second preference is for $drink_1<BR>';
echo "I like $drink_1";
?>

The output of the above code will look like

My first preference is for Tea
My second preference is for $drink_1
I like Coffee

I hope this example was clear enough and by now you might have a better understanding of difference between using a single quotes('') and a double quote ("").

In our next section, printing strings, we will revisit the difference between using a single quote and double quote with examples and also look at printing the values of variables. Ready? Let's go to Printing Strings.



Printing Strings in PHP

In this section, we will learn to print strings. Also, see how to print values of variables along with strings, with help of some examples.

Simple Printing

Simple printing in PHP means that we will assign a string to a variable and print it's value in the output. Let us begin with this simple example.

<?php
echo "This is a string";
//Output- This is a string

echo "String
in
multiple lines
also work";
//Output- String in multiple lines also work

echo "Let's rock";

//writing the above using single quote
//will not work without a escape character
//in this case it is a backslash \

echo 'Let\'s Rock';
//Try the above without a \ and see the difference!

echo 'First line \n Second line'; //will not work - single quote

echo "New line \n second line"; //will work - double quotes
?>

In the above example, we used a backslash when we enclosed the string 'Let's Rock' in single quote. This is called escaping. This is essential when you want to avoid PHP from processing certain portion of code. For example, if you can put \ in front of variable $string in your echo statements to avoid printing the value of the variable, such as \$string. Sometimes, you may have to put more backslashes, like \\\$string

Printing Variables

We will now look at assigning a string to a variable and printing it's value as an output. See this example:

<?php
$string = '100 pages'; //Assigning a string to a variable

echo 'I want to print $string';
//Output: I want to print $string

echo "I want to print $string";
//Output: I want to print 100 pages

echo "I will print $string's";
//this will work as a variable name can not have
//the ' character!

echo "I will print $strings";
//will not work, it will look for a variable name $variables

echo "I will print {$string}";
//will work, {} are not considered as part of variable names

echo "I will print ${string}";
//will work, {} are not considered as part of variable names
?>

You must try to experiment with the above code and modify it to see how it works. That will be a great learning experiencing for you!

Let's also take a look at some built-in constructs of PHP that we can make use of to print one or more strings. SOme of these are:

  • print and

  • printf

These built-in constructs can be used in the same way we use 'echo' to print strings.

We will now move on to our next section on String Comparison

String Comparisons in PHP

Comparing Strings

String comparison is one of the most important part of strings related coding that you might do in your projects. It's very easy to understand but you will have to remember some key differences when using comparison operators while comparing strings.

As usual we will begin with an example but in this case I will include 2 different examples in one set to show you the difference in output of comparison when using different comparison operators.

<?php //Example 1 with '==' comparison operator
$a 0;

if ($a == "Zero") {
  echo 'True';
  } else {
  echo 'False';
  }
?>

<?php //Example 2 with '===' comparison operator
$a 0;

if ($a === "Zero") {
  echo 'True';
  } else {
  echo 'False';
  }
?>

Above, in example #1, I have used '==' operator, which is evaluating if the value on right hand side is equal to value on left hand side. I guess, you expected the output to be 'False'? No, that's not the case. The output is 'True'. Strange? Not really!

Always remember, when comparing strings, you should use '===' operator (strict comparison) and NOT '==' operator (loose comparison). When comparing an integer with a string, the string is converted to a number. And if you compare two numerical strings, they are compared as integers. Now try to replace $a == "Zero" with $a == "00" in the first example and see the results.

Using built-in function to compare- strcmp()

One other way of doing string comparison is using the PHP built-in function called strcmp(). This comparison is case-sensitive and the syntax of this function is:

strcmp ( string str1, string str2 )

It will return the following after comparison and your further processing should be based on this output:

Returns < 0 if str1 is less than str2
Returns > 0 if str1 is greater than str2
Returns 0 if they are equal

Refer to the example below to see usage of strcmp():

<?php
$a "First";
$b "Second";
$c "Third";
$str "Third"//Third with a capital 'T'
$str1 "third"//third with a small 't'

$d strcmp($a,$b); //storing the output of strcmp in $d
echo $d//Output: -1 ($a is less than $b)

$d strcmp($b,$c);
echo $d//Output: -1 ($b is less than $c)

$d strcmp($c,$str);
echo $d//Output: 0 ($c and $str are equal)

$d strcmp($str,$str1); //Comparing third with Third
echo $d//Output: -1 ($str is less than $str1)

//Another usage is

if (strcmp($c$str) == 0) {
    echo "strings are equal";
    } else {
    echo "string are not equal";
    }
?>

For case-insensitive comparison use the strcasecmp() function instead. Just replace the function name in above example and test the results.

Alright, let's move on to String Manipulation.


Manipulating Strings in PHP

String Manipulation in PHP

In this section, we will learn different ways of manipulating string through PHP coding. Some of these are basic coding techniques while some will require using built-in functions of PHP for advance string manipulation.

String Concatenation

One of the most simplest string manipulation activity that can be done is concatenating two or more strings to form a single string. For example: $a might hold a string called "First" and $b might hold a string called "Second". To concatenate these two strings into one, we use a '.' (dot). See this example:

<?php
$a "First";
$b "Second";
$c "Third";

echo $a $b//using a . (dot) in between $a and $b

echo $a $b $c//three strings together

$d $a $b//concatenating $a, $b and storing in $d

echo $d//printing $d

echo "\$a is holding a string called"." ".$a;  
?>

Change the case of a string to lowercase and UPPERCASE

That's quite easy! All we need to do is use the built-in function called strtolower() to convert a string to lowercase and strtoupper() for uppercase conversions. See the example to convert a string to lowercase and uppercase.

<?php
$string "PHP is a GREAT Programming Language!";
$new_string strtolower($string);

echo $new_string;
//Output: php is a great programming language!

$new_string strtoupper($string);

echo $new_string;
//Output: PHP IS A GREAT PROGRAMMING LANGUAGE!
?>

Now, use the above example but replace the used functions with ucwords() (Uppercase the first character of each word in the string) and also ucfirst().

Determining position of first occurrence of a string

This is easy one! We will use yet another handy built-in function called strpos(). The syntax of strpos() is:

strpos ( string, keyword [, int offset] )

This will return 'FALSE' if the keyword is not found in the string and you will have to use '===' (strict comparison) to check the returned value. See the below example for usage of strpos().

<?php
$string "PHP is a GREAT Programming Language!";
$keyword "GREAT";

#Searching for keyword in the string
$position strpos($string$keyword);

echo $position//Output: 9 (9th position of Keyword)
?>

<?php
#conditional usage of strpos()
$string "This is a simple string";
$keyword "simple";
$keyword_1 "MySQL";

if (strpos($string$keyword) > ) {
    echo "String found";
    } else {
    echo "String not found";
    }
?>

<?php
#conditional usage of strpos()
$string "This is a simple string";
$keyword "MySQL";

if (strpos($string$keyword) > ) {
    echo "String found";
    } else {
    echo "String not found";
    }
?>

Return portion of a string from a given string

To get portion of a string from a given string we will make use of substr() function of PHP. The syntax is:

substr ( string , int start [, int length] )

Remember, the position of the first character of the string is always '0'. The function will take the start position and return a portion of the string from the start position as specified. You may optionally also mention the end position till which you want to get the portion of any given string. For example, in the string "Hello", the letter 'H' is at position '0' and the letter 'o' is at position '4'. See this example:

<?php
$string "PHP is GREAT Programming Language!";

#Returning portion of the above string from 0 to 12
$str substr($string,0,12);

echo $str//Output: PHP is GREAT (includes two spaces as well)

#Let's also concatenate something to $str

echo $str." Programming Language!";
?>

Adding slashes to string

Under various circumstances, you will need to automatically add slashes to escape special characters in a string. Be it storing in database table, or for anything else. Here's how we can do it with built-in addslashes() function. The syntax is:

addslashes ( string )

Below is an example to add slashes to any given string.

<?php
$string "Let's learn PHP. It's fun!";
$new_string addslashes($string);
echo $new_string//output: Let\'s learn PHP. It\'s fun!

#You can also do this directly without storing it in $new_string
echo addslashes($string); //works too! 
?>

That's all folks! We will later on add more examples here. You may visit the examples section for other examples. With this section, we have completed our session on Strings in PHP.


Arrays in PHP

Welcome to the world of Arrays! In this section we will learn about Arrays, Types of Arrays, Storing and Retrieving data from Arrays with examples and explanation.

What is an Array?

An array is a like a list or a group of similar elements which stores data elements of a specific data type. These data elements are stored in a series inside the array and each of these stored data element has its own position in the Array by which it is referred to and retrieved. The position of these stored elements is maintained by the Index of the Array which is usually made up of consecutive integers beginning at zero. The values which are used to index the elements in an array are unique. That means, you can have only one unique value as an indexer (Key) and no two data elements in an array will have same indexer or the key.

See this example:

Name

John

Greg

Romeo

David

Chris

The above list consists of names of individuals. Note that the position of the first name is starting with zero. Let's see another example of a list.

Protocols

TCP

IP

FTP

SMTP

POP3

DNS

That was a list of some of the protocols which are most widely used on Internet. Note that the position of the first protocol 'TCP' in the list is zero. Read the next topic on Types of Arrays.


Types of Arrays in PHP

In PHP, there are two types of Arrays. One is Numerical or Indexed Array and the Associative Array.

In Numerical or an Indexed Array, the indexer of the array which is used to determine the position (also known as Key) of the stored data element is an integer which begins at zero. Consider this example:

Position in Array

Name

0 =>

TCP

1 =>

IP

2 =>

DNS

3 =>

HTTP

4 =>

FTP

5 =>

SMTP

In the left column, we are displaying the position of the name of the protocol that is on the right hand side. The position is an integer and is starting at zero. So, if you were to retrieve the name of the protocol which is at 4th position, then the Array will return 'FTP' and not 'HTTP'. In this way PHP uses integers as indexers or the key to store and determine the position of the data element in the Array. So how is it different from an Associative array?

In Associative array, the key or the indexer of the array which is used to refer to the data element is a string and not an integer. Consider this example:

Abbreviation

Expanded Term

TCP =>

Transmission Control Protocol

IP =>

Internet Protocol

DNS =>

Dynamic Naming System

HTTP =>

Hyper Text Transfer Protocol

FTP =>

File Transfer Protocol

SMTP =>

Simple Mail Transfer Protocol

In the above example as you can see, we have used strings and not integers to determine the position of the data elements. So, if we query the array for the data element which is stored at the position of 'SMTP' (our key for the data element), the array will return 'Simple Mail Transfer Protocol'.

To summarize, Indexed arrays have integers as their key values while Associative arrays have strings as their keys. Let's move on to our next topic Creating arrays in PHP.


Creating Arrays in PHP

Creating an array in PHP is a simple task. An array() construct is used in PHP to create an array. Here are couple of examples with explanation for better understanding:

We first start with creating an Indexed or Numerical Array which is quite simple. Remember, all you have to do is use the array() construct. In this example, we will create an indexed array consisting of some protocols (our data elements). The position of first indexed element will be by default zero unless we change it.

<?php //Example 1
$protocols = array("TCP""IP""DNS""FTP""SMTP");
//TCP, IP, DNS, FTP and SMTP are data elements of the array
?>

Ok, we have got the array created but how do we know what position are the elements stored inside the array? How do we know what elements are actually stored in the array? It's simple. We will have to make use of print_r() construct in PHP which make our job easy. Here's how:

<?php //Example 2
$protocols = array("TCP""IP""DNS""FTP""SMTP");
print_r($protocols); //using the print_r() construct
//Output: Array ( [0] => TCP [1] => IP [2] => DNS [3] => FTP [4] => SMTP ) 
?>

Look at the output of above code. At the first position is TCP and the first position is having an integer value of zero which is our key to this array. We used print_r() to print the elements of the array and their positions. If the data elememnts stored are very large in number consider not using the print_r() as it will fill up your screen with its output. Now let's take a look at another way of creating the same array in example #2.

<?php //Example 3
$protocols[0] = "TCP";
$protocols[1] = "IP";
$protocols[2] = "DNS";
$protocols[3] = "FTP";
$protocols[4] = "SMTP";
print_r($protocols);
//Output: Array ( [0] => TCP [1] => IP [2] => DNS [3] => FTP [4] => SMTP )
?>

Ok, we are now familiar with both the ways of creating an indexed array, now let's take a look at creating an Associative array. Remember, in associative array, the key value used for storing the position of an elements inside the array is a string but not an integer.

<? //Example 4
$protocol['TCP'] = "Transmission Control Protocol";
$protocol['DNS'] = "Dynamic Naming System";
$protocol['IP']  = "Internet Protocol";
$protocol['FTP'] = "File Transfer Protocol";
print_r($protocol);
//Output: Array ( [TCP] => Transmission Control Protocol 
//[DNS] => Dynamic Naming System [IP] => Internet Protocol 
//[FTP] => File Transfer Protocol ) 

//Associate array creation can also be done using array() construct

$months = array('Jan'=>"January"'Feb'=>"February"'Mar'=>"March");
print_r($months);
//Output: Array ( [Jan] => January [Feb] => February [Mar] => March )

echo $months['Jan']; //Referring an individual element of the array
//Output: January
?>

In an associative array we refer to position of a stored data element by the key of the index which is a string. But then, you can always have a string like "01", "02" as the key or index for elements of an array. It's just that "01" and "02" are considered as strings but if all the key values were mentioned as integers such as 1, 2 ,3 ,4 then the index will consist of all numerical values which will make it an indexed array.

There are certain requirements some times due to which you may not want an indexed array to have it's starting index number as zero instead you may want to begin your index at 1. Such is a requirement when you want to store all months in an array and we all know month numbers starts with 1 and not zero. Here is how we do it:

<? //Example 5
$months = array(1=>"Jan""Feb""Mar""Apr""May""June""July""Aug",
"Sep""Oct""Nov""Dec");
print_r($months);
//Output: Array ( [1] => Jan [2] => Feb [3] => Mar [4] => Apr [5] => May 
// [6] => June [7] => July [8] => Aug [9] => Sep [10] => Oct 
// [11] => Nov [12] => Dec ) 
?>

In the above example we manually specified numerical value of the first position in the array. The remaining values were automatically incremented based on the first key value. You can mention any other number as the first key value and not necessarily it has to start with 0 or 1. Only in case of an indexed array where a starting key value is not specified, it's automatically started with a zero.

Now that we are familiar with creation of both indexed and associate arrays, let's look at some common and simple tasks related to arrays.

How to assign a range of values to an array?

To accomplish this task we will make use of the range() function, usage of which is fairly simple and straight. Check this example:

<? //Example 6
$alphabets range('a','z'); 
// The above will hold all alphabets from a to z, key starts at 0

$numbers range (1100);
//All numbers from 1 to 100, key starts at 0
?>

Determining the size of an array?

Often, you would come across some or the other requirement in your coding to first find the size of an array (number of elements) and then do some looping to retrive values or perform some other array related operation. Use count() or sizeof() functions for this purpose. It's simple:

<? //Example 7
$alphabets range('a','z'); 
// The above will hold all alphabets from a to z, key starts at 0
echo count($alphabets); //Output: 26

$numbers range (1100);
//All numbers from 1 to 100, key starts at 0
echo count($numbers); //Output: 100
?>

Let's take a look at some very basic and most commonly used array related tasks in next topic Array Operations.


Array Operations in PHP

In this section we will see some most commonly used array functions, their usage with examples.

Split an array into chunks

To split an array into smaller chunks or smaller sized arrays, we use array_chunk() function of PHP. This will return arrays of several smaller sizes and each array's index number will start with zero unless you want to use the preserve_keys parameter to preserve the original index numbers from the input array used. The syntax is:

array_chunk ( array input, int size [, bool preserve_keys] )

Using the above function in an example:

<?
$my_array = array("One""Two""Three""Four");
$split_array array_chunk($my_array2);
print_r($split_array);
//Output: Array ( 
//                [0] => Array ( 
//                              [0] => One 
//                              [1] => Two ) 
//                [1] => Array ( 
//                              [0] => Three 
//                              [1] => Four ) 
//                               ) 
?>

Combine an array with data elements and other with its keys

We can create an array by combining one array with keys and second array with corresponding data elements. Note that the number of keys and data elements in both the arrays has to be equal for this operation to be successful. We will make use of built-in function array_combine(). Its syntax is:

array_combine ( array keys, array values )

and the example using array_combine() is:

<?
$keys_array = array(1,2,3,4);
$data_array = array("one","two","three","four");
$new_array array_combine($keys_array$data_array);
print_r($new_array);
//Output: Array
// (
//     [1]  => one
//     [2]  => two
//     [3]  => three
//     [4]  => four
// )
?>

Merging two or more arrays

Using an built-in function array_merge() we can merge two or more arrays to form a single array. The values from the second array are appended at the end of first array and so on. So, if three arrays are to be merged, elements from third will be appended at the end of second array and then it will be appended at the end of the first array. Take a look at this syntax and example:

array_merge ( array array1 [, array array2 [, array ...]] )

<?
$first_array = array(1,2);
$second_array = array(3,4);
$third_array = array(5,6);

$merged_array array_merge($first_array,$second_array,$third_array);
print_r($merged_array);
//Output: Array 
//          ( [0] => 1 
//            [1] => 2 
//            [2] => 3 
//            [3] => 4 
//            [4] => 5 
//            [5] => 6 
//          ) 
?>

Searching an array

Searching for a value in an array is made simple using the function array_search(). If the keyword is found in the array, then the corresponding key of that value is retured for further operations. The syntax and example are:

array_search ( keyword, array name )

<?
$months = array(1=>"Jan""Feb""Mar""Apr""May""June""July""Aug",
"Sep""Oct""Nov""Dec");
$key array_search("May"$months); //Searching for May in months array
echo $key;
// We can also print the value that key points at
echo $months[$key];
?>

With that example we wrap up our section on Arrays in PHP.


Database Access


Here’s a quick example of how to access Symposium data:


$dbhsccs = sybase_connect("10.25.238.1", "readonly", "readonly") or die ("Unable to connect to server");

sybase_select_db("blue") or die ("Unable to select database.");

$query = sybase_query("select * from Agent");

while($row = sybase_fetch_row($query)) {
print “$row[0]<BR>\n”;

}

sybase_close($dbhsccs);

}