PHP Strings Common PHP String Functions Substring Examples

PHP String

A string is an important data type in any programming language, used to manipulate informative data using different methods. PHP strings can be of any length, since there is no limits to the size of strings in PHP. The PHP strings can be specified using either single quote (ex. 'This is test string') or using double quotes (ex. "test string"). As compared with double quoted strings in single quoted PHP string variable will not be parsed and such string have only one escape character, single quote. Like any other programming languages, PHP also has some in built string manipulation functions. These PHP functions can directly be used in our code or other powerful functions can be derived using these basic string functionalities. Following is the list of some commonly used PHP functions along with examples.

Finding length of a PHP string using strlen

The strlen PHP string function is used to find the length of the given string. for example
$str = 'test string'; 
$len = strlen('$str');
echo $len; // this will output 11

Checking substring existence using strpos

PHP string function strpos can be used to check for substring existence. See example below:
$str = 'test string';
$sub_str = 'str';
if (strpos($str, $sub_str) === false) 
 echo "Substring not found";
 echo "Substring exist in given string";
Note the use of === operator because == will not work as expected since the return position can be 0 (start of string).
The offset value can be used here to specify from where to start searching. see example below:
$str = 'abcdefabcdef';
echo strpos($str, 'a', 1); // will print 6 not 0

Finding occurrence of a string

The strstr PHP string function is used to find the first occurrence. See below
$email = 'user@domain.com';
$domain = strstr($email, '@');
echo $domain; // this will print '@domain.com'
So strstr will return part of the string, starting from the given substring. If given substring does not exist, it will return FALSE. This string function is case-sensitive. For case-insensitive searches stristr is used , see below:
$domain = stristr('USER@EXAMPLE.com', 'e');
echo $domain; // This will print ER@EXAMPLE.com
Function strrchr(string str, char chr) is used to find the last occurrence of a character. This function returns the portion of string which starts at the last occurrence of given character and goes up to the end. see example below:
echo strrchr("abcdexyz", "e"); // will print exyz
echo substr(strrchr("module.filename.html", "."),1); // will print html

Return part of a string: Substring

The PHP function substr( string string, int start [, int length]) can be used to return part of a given string specified by start and length parameters. see examples below:
echo substr("abcdef", 1);    // will output "bcdef" , start 1 to end.
echo substr("abcdef", 1, 3); // will output "bcd", 1 to 3
echo substr("abcdef", 0, 4); // will output "abcd"
echo substr("abcdef", 0, 8); // will output "abcdef"
Using curly braces we can also return a character at given position. For example
$string = 'abcdef';
echo $string{0}; // will print a
echo $string{3}; // will print d
We can also use negative value of start parameter to return part from the end of string. see examples below:
substr("abcdef", -1);    // returns "f"
substr("abcdef", -2);    // returns "ef"
substr("abcdef", -3, 1); // returns "d"
Also negative value of length parameter can be used. In this case it will omit that many characters from the end of the string. See below:
echo substr("abcdef", 0, -1);  // will omit 1 char from the end and returns "abcde"
echo substr("abcdef", 2, -1);  // returns "cde"
echo substr("abcdef", 4, -4);  // returns ""
echo substr("abcdef", -3, -1); // returns "de"


PHP HTML Forms Using HTML Form Fields Hidden Radio Buttons Checkboxes

PHP is widely used today as server side scripting language. It is mostly used to develop interactive web sites and can easily be embedded in HTML. The interaction between user/browser and the server is carried out using the HTML forms. One of the most powerful features of PHP is the way it handles HTML forms. This tutorial explain using HTML form fields like Input, Hidden, Radio Buttons, Check boxes etc. The basic concept that is important to understand is that any form field values in a form will automatically be available to your PHP scripts. HTML forms can be submitted to the handling PHP script using either GET or POST method. See example below:

When we submit above form autoglobal $_POST['first_name'] and $_POST['last_name'] automatically available to the form handling PHP script. Similarly if GET method is used then $_GET['first_name'] and $_GET['last_name'] is available. Following example shows how we can access values in handling PHP script i.e. in action.php

There are various types of input elements are used in HTML form. Following is the list of such elements used to accept inputs from user/broswer that needs to be sent to the web server for further processing:

Text input, Hidden input and Password type input fields

This input form element can be used for a single lime text input from the user. For example user first name, user e-mail, phone numbers etc. The syntax in HTML form is as below

This will display an input box in the browser and the values of this element canbe accessed at the form handling php script by following.

Password type The defulat type of HTML input element is text. The special password type of input can be used as following

and can be accessed in PHP similar to above input element.

Hidden type The hidden field is used to send information from browser to the server without having to input it. Typically this is used to send some logical data that has nothing to do with user but used at the server in PHP program logic. For example state, action, or passing the result to the other module etc. Please note that you encode the value using htmlspecialchars() function.

and the value of this field can be accessed in PHP by following.

Textarea multiline text input HTML form element in PHP

This form element can be used for a multi-line text input from the user. For example product description. The syntax is as below.

This will display a multi-line input area in the browser and the size can be controlled using rows and cols tag. The text value input by user can be accessed in PHP by following

Select (Pull Down menu) and Select multiple options in PHP

This type of HTML form element is used to allow user to select from multiple choices. For example selecting a month or a day. The html syntax is as below.

The value of selected choice can be accessed in form handling PHP script as following

The variation to this allows user to select multiple choices from the given options. This can be done by following select multiple syntax

The size tag can be used to control how many rows should be visible. And note the use of '[]' following the name of the select box. This will denote that it is an array and the choices can be accessed in form handling PHP script by following.

Radio buttons HTML form element

Radio button in HTML form is an alternative method that allows user to select from given options. Unlike drop down menu this is used to create more visibilty in the input form.

The value of the selection can be accessed in PHP as following

Check Boxes HTML form element

This is an alternative way of allowing user to select multiple choices from the given options. Following example show the use of Check Boxes in an HTML form

Again here PHP array is used to access the selected choices from the user.


PHP Elements PHP Language Reference PHP Quick Reference

The first step learning any programming language is to know about the language reference elements. PHP is a scripting language that is suited for Web application development and is widely used today. Like any other programing language PHP consists of following basic language elements which are very similar to 'c' language. Here is the quick PHP Language Reference.

PHP Variables

Variables in PHP are represented by a $ sign followed by the name of the variable and is case-sensitive. PHP variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. Examples $a, $user_name, $_xclick.
  • Assinging value to variable $a = 2; , $b = $a + 2; , $user_name = "White";
  • Value by reference: '&' is used to referance a variable. In following examle $b is point to $a
Predefined variables: PHP Superglobals are available to any running PHP script. Following is the list of PHP Predefined variables.
  • $GLOBALS Contains a reference to every variable which is currently available within the global scope of the script. The keys of this array are the names of the global variables.
  • $_SERVER Variables set by the web server or otherwise directly related to the execution environment of the current script.
  • $_GET Variables provided to the script via HTTP GET.
  • $_POST Variables provided to the script via HTTP POST.
  • $_COOKIE Variables provided to the script via HTTP cookies.
  • $_FILES Variables provided to the script via HTTP post file uploads.
  • $_ENV Variables provided to the script via the environment.
  • $_REQUEST Variables provided to the script via the GET, POST, and COOKIE input mechanisms.
Variable scope
  • For the most part all PHP variables only have a single scope. See example below:

    In above example $user is available to main.php also.
  • PHP Variable used inside a function is limited to the local function scope. For example:

    The global keyword is used in this case to refer to variable $user. See Below:

  • A static variable exists only in a local function scope, it retain its value when program execution leaves this scope. see example below:

    Everytime Test() is called it increments the value of $a and prints it. First time will print 1, second time 2 and so on.
  • Variable variable names takes the name of the variable from other variable. See Below:

PHP Constants

define() functin is used to create constants in PHP. Its value cannot be changed during the execution of the script and they are having global scope and accessed anywhere in the script. See exampe Below:

Predefined constants PHP provides some special constants which are case-insensitive and are as follows:
  • __LINE__ current line number of the file.
  • __FILE__ full path and filename of the file.
  • __FUNCTION__ function name
  • __CLASS__ class name.
  • __METHOD__ class method name

PHP Data Types

PHP supports followin Data types
Standard Data Types
  • Integer Integers are signed or unsigned whole numbers can be specified in decimal (10-based), hexadecimal (16-based) or octal (8-based). See Examples Below:

  • floats/doubles/real numbers Floating point numbers can be specified using any of the following:

  • String String data type is a collection of characters. backslash (\) is an escape character. Following are some string examples

  • Boolean It can be either TRUE or FALSE and case in-sensitive. See Below

  • Object This is an instance of a class. The new statement is used to instantiate the object to a variable. See Below

  • Array An array in PHP is an ordered map that maps values to the keys. See examples below:

Special Data Types
  • Resource A resource is a special variable, holding a reference to an external resource. A reference handlers to opened files, database connections, image canvas for example.
  • NULL An uninitialized variable, represents that a variable has no value

PHP Operators

Arithmetic Operators
  • = Assignment, for example $a = 5; , $a = $b+5;
  • + Addition for example $a+$b
  • - Subtraction for example $a-$b
  • / Division for example $a/$b
  • * Multiplication for example $a*$b
  • % Modulus for example $a%$b
Comparison Operators are used to perform tests on their operands and they return true or false based on the value of operands.
  • == Equal to for example $a == $b
  • != Not Equal to $a != $b
  • <> Not Equal to $a <> $b
  • === Equal to and of same type for example $a === $b
  • !== Not Equal to or they are not of the same type $a !== $b
  • > Greater than for example $a > $b
  • >= Greater than or equal to for example $a >= $b
  • < Less than for example $a < $b
  • <= Less than or equal to for example $a <= $b
Bitwise Operators
  • & And Bits, $x = $a & $b; will set bits in $x which are set in both $a and $b
  • | Or Bits, $x = $a | $b; will set bits in $x which set in either $a or $b
  • ^ Xor Bits, $x = $a ^ $b; will set bits in $x which set in $a or $b but not in both
  • ~ Not Bits, $x = ~ $a; Reverse bits of $a i.e. 1 to 0 and 0 to 1
  • << Shift left, $a << 4; Shifts bits of $a 4 steps to left
  • >> Shift right, $a >> 3; Shifts bits of $a 3 steps to right
Logical Operators
  • and, && And, ($a>1) && ($a<5) TRUE if both are true
  • or, || Or, ($a>1) or ($a<5) TRUE if either is true
  • xor Xor, ($a>1) xor ($a<5) TRUE if either is true but not both
  • ! Not, !$a TRUE if $a is not true
Increment/decrement Operators
  • ++$a Increments $a by one, then returns $a
  • --$a Decrements $a by one, then returns $a
  • $a++ Returns $a, then increments $a by one
  • $a-- Returns $a, then decrements $a by one
Other Operators
  • @ This is an error control operator when prepended to an expression any error messages that might be generated by that expression will be ignored
  • `` This is an execution operator will execute the contents of the backticks as a shell command for example $a = `ls`; will return the ourput of ls shell command.
  • . This is a string operator which returns the concatenation of its right and left strings for example $c = $a."Some String"
  • .= This is a string concatenating assignment operator for example $a .= "Some String" will append "Some String" to the right of $a

PHP Control Structures

  • if allows for conditional execution of code fragments. see example below
  • else extends an if statement to execute a statement in case the expression in the if statement evaluates to FALSE. see example below
  • elseif / else if unlike else, as its name suggests, it will execute alternative code only if the elseif condition is TRUE. see example below
  • switch is used to compare the same variable with many different values, and execute a different code depending on value of variable or expression. see example below

    This is equivalent to a series of if..elseif statements and "break" statement is used to terminate the execution of code for the given case.
  • Alternative syntax for Control Structures is to change the opening brace to a colon (:) and the closing brace to endif;, or endswitch; see example below

PHP Functions

  • Defining a Function in PHP can be done using function statement. see below

    A return statement is used to return values from the function
  • Function with an Optional Argument can be defined using following

    In above function $id is optional and if given will be appended to the returning url.
  • Making arguments be passed by reference allows the function to change its argument which is not possbile when it is passed by value. This is done by '&' see below

PHP Coding

A code in any programming language is a series of statements. A statement can be an assignment, a function call, a loop, a conditional statement of even an empty statement which does nothing. In PHP a statement is terminated with semicolon(;). Multiple statements can be grouped using the curly braces ({...}). // and /*..*/ is used to insert comments in PHP. See example below

Embedding PHP in HTML: PHP is especially suited for Web development and can be embedded into HTML. This can be done by using some special start and end tags. See example below


Introduction PHP Introduction PHP MySql Introduction

PHP Intoroduction

PHP is widely-used today as a scripting language in dynamic web site development. It is an Open Source scripting language best suited for dynamic web page development and can easily be embedded into HTML. PHP is mainly focused on server-side scripting, so you can do anything, such as collect form data, generate dynamic page content, or send and receive cookies. But PHP can do much more.

PHP is a server side language that is executed on the server and client will only know the result of the script without knowing the underlying PHP code. The best thing of PHP is that it is very simple to learn but it offers many advanced features. We can use PHP for simple web page development to a very highly sophisticated erp applications.

PHP MySql Intoroduction

One of the biggest advantage of using PHP is how easily it interacts with the underlying database system. Using PHP MySql combination, writing a database-enabled web page is incredibly simple. One of the strongest and most significant feature in PHP is its support for a wide range of databases. It supports Ingres, Oracle, d Base, PostgreSQL, mSQL, MS-SQL, Sybase, MySQL and many other. Although PHP supports these many databases, MySQL an Open Source RDBMS, is commonly used today because it runs easily on Windows and UNIX and for many other reasons. MySQL supports most of the functionality those are in a commercial RDBMS. One major area where MySQL falls short was its lack of support for stored procedures and triggers. However, both of these features are included in the current release 5.0. MySQL database is used to store and organize information on the web and PHP is used to extract and include these information into the web pages.