You are on page 1of 54

PHP conditional events and loops :

PHP conditional statements: In this article, we are going to learn about the various
conditional statements in PHP programming language with examples.
Submitted by Kongnyu Carine, on May 20, 2019

PHP Conditional Statements


While coding, you may get to a point where your results can only be gotten when a condition
is valid. We make use of conditional statements. Conditional statements are statements that
can only be executed based on the fulfillment of a particular condition(s).

There are basically 4 different types of conditional statements in PHP,

1) The if statement
With the if statement your code only executes only when the condition is true.

Syntax:

if(condition){
//code to be executed when condition is true
}

Example:

Let's check if a mark entered is greater than or equal to 80. If true an A grade is given.

<?php
//defining a variable
$mark = 120;
if($mark >= 80){
echo "you have an A";
}
?>

Output:you have an A

2) The if...else statements


The if...else statement is used when a condition is satisfied and when it is not satisfied. So
it's used when the condition is either true or false.
Syntax:

if (condition){
//code to be executed when true }
else {
//code to be executed when false
}

Example:

Here, we are going to check if the letter entered is an F which will display female else we
display male.

<?php
//defining a variable
$gender = 'F';
if ($gender == 'F'){
echo "FEMALE";
}
else {
echo "MALE";
}
?>

Output:FEMALE

3) The if...elseif...else statements


In a situation where you have several conditions, for example a program to grade students
based on their marks with the letters A, B, C, D, F. the if...elseif...else is used for this.

Syntax:

if (condition1){
//code 1 to be executed
}
elseif(condition2) {
//code 2 to be executed
}
else{
//code to be executed if code 1 and code 2 are not true
}

Example:

We are going to grade students with the letters A, B, C, D, F based on their marks on 100.

PHP Code:
<?php
//defining a variable
$marks = 75;

if ($marks>79){
echo "A";
}
elseif($marks<=79&& $marks>60) {
echo "B";
}
elseif($marks<=60&& $marks>50) {
echo "C";
}
elseif($marks=50) {
echo "D";
}
else{
echo "F";
}

?>

Output:B

4) The nested if...else statements


When you find if...else statements inside an if...else statement the statements are nested.
With this statement, you can get alternatives results when a condition is true or false.

Syntax:

if (condition 1 )
{
if (condition 2 )
{
// code1 to be executed
}
else
{
// code 2 to be executed
}
}
else
{
// code 4 to be executed
}

Example:
Let's compare tow numbers using the nested if statement.

<?php

// defining variables
$number1 = 40;
$number2 = 12;

if ($number1 != $number2) {
echo 'number1 is different from number2';
echo '<br>';
if ($number1 > $number2) {
echo 'number1 is greater than number2';
} else {
echo 'number2 is greater than number1';
}
} else {
echo 'number1 is equal to number2';
}
?>

Output
number1 is different from number2
number2 is greater than number1

5) The switch statement


The switch statement is very similar to the if...else statement. But in the cases where your
conditions are complicated like you need to check a condition with multiple constant values,
a switch statement is preferred to an if...else. The examples below will help us better
understand the switch statements.

Syntax:

switch (n)
{
case constant1:
// code to be executed if n is equal to constant1;
break;
case constant2:
// code to be executed if n is equal to constant2;
break;
.
.
.
default:
// code to be executed if n doesn't match any constant
}
Example:

Let's rewrite the example of if…..else statements using switch statements,

<?php
//variable definition
$gender = 'M';
switch ($gender)
{
case 'F':
echo 'F is FEMALE';
break;
case 'M':
echo 'M is MALE';
break;
default:
echo 'Invalid choice';
}
?>

Output : M is MALE

Looping
Loops in PHP are used to execute the same block of code a specified number of times. PHP
supports following four loop types.

● for − loops through a block of code a specified number of times.


● while − loops through a block of code if and as long as a specified condition is true.
● do...while − loops through a block of code once, and then repeats the loop as long as
a special condition is true.
● foreach − loops through a block of code for each element in an array.

We will discuss about continue and break keywords used to control the loops execution.

● The for loop statement


The for statement is used when you know how many times you want to execute a statement
or a block of statements.

Syntax
for (initialization; condition; increment){
code to be executed;
}
The initializer is used to set the start value for the counter of the number of loop iterations. A
variable may be declared here for this purpose and it is traditional to name it $i.

Example
The following example makes five iterations and changes the assigned value of two
variables on each pass of the loop −

Live Demo
<html>
<body>

<?php
$a = 0;
$b = 0;

for( $i = 0; $i<5; $i++ ) {


$a += 10;
$b += 5;
}

echo ("At the end of the loop a = $a and b = $b" );


?>

</body>
</html>
This will produce the following result −

At the end of the loop a = 50 and b = 25

The while loop statement


The while statement will execute a block of code if and as long as a test expression is true.

If the test expression is true then the code block will be executed. After the code has
executed the test expression will again be evaluated and the loop will continue until the test
expression is found to be false.
for loop in PHP
Syntax
while (condition) {
code to be executed;
}
Example
This example decrements a variable value on each iteration of the loop and the counter
increments until it reaches 10 when the evaluation is false and the loop ends.

Live Demo
<html>
<body>

<?php
$i = 0;
$num = 50;

while( $i < 10) {


$num--;
$i++;
}

echo ("Loop stopped at i = $i and num = $num" );


?>

</body>
</html>
This will produce the following result −

Loop stopped at i = 10 and num = 40

The do...while loop statement


The do...while statement will execute a block of code at least once - it then will repeat the
loop as long as a condition is true.

Syntax
do {
code to be executed;
}
while (condition);
Example
The following example will increment the value of i at least once, and it will continue
incrementing the variable i as long as it has a value of less than 10 −

Live Demo
<html>
<body>
<?php
$i = 0;
$num = 0;

do {
$i++;
}

while( $i < 10 );
echo ("Loop stopped at i = $i" );
?>

</body>
</html>
This will produce the following result −

Loop stopped at i = 10

The foreach loop statement


The foreach statement is used to loop through arrays. For each pass the value of the current
array element is assigned to $value and the array pointer is moved by one and in the next
pass next element will be processed.

Syntax
foreach (array as value) {
code to be executed;
}
Example
Try out following example to list out the values of an array.

Live Demo
<html>
<body>

<?php
$array = array( 1, 2, 3, 4, 5);

foreach( $array as $value ) {


echo "Value is $value <br />";
}
?>

</body>
</html>
This will produce the following result −
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5

The break statement


The PHP break keyword is used to terminate the execution of a loop prematurely.

The break statement is situated inside the statement block. It gives you full control and
whenever you want to exit from the loop you can come out. After coming out of a loop
immediate statement to the loop will be executed.

PHP Break Statement


Example
In the following example condition test becomes true when the counter value reaches 3 and
loop terminates.

Live Demo
<html>
<body>

<?php
$i = 0;

while( $i < 10) {


$i++;
if( $i == 3 )break;
}
echo ("Loop stopped at i = $i" );
?>

</body>
</html>
This will produce the following result −

Loop stopped at i = 3

The continue statement


The PHP continue keyword is used to halt the current iteration of a loop but it does not
terminate the loop.

Just like the break statement the continue statement is situated inside the statement block
containing the code that the loop executes, preceded by a conditional test. For the pass
encountering continue statement, rest of the loop code is skipped and next pass starts.

PHP Continue Statement


Example
In the following example loop prints the value of array but for which condition becomes true it
just skip the code and next value is printed.

Live Demo
<html>
<body>

<?php
$array = array( 1, 2, 3, 4, 5);

foreach( $array as $value ) {


if( $value == 3 )continue;
echo "Value is $value <br />";
}
?>

</body>
</html>
This will produce the following result −

Value is 1
Value is 2
Value is 4
Value is 5

Exit:
An exit statement is used to terminate the current execution flow.
As soon as exit statement is found, it will terminate the program.
It can be used to output a message and terminate the current script: for example exit(“Good
Bye!”);
It can also be used with error code. For example: exit(1), exit(0376).
the following program demonstrates the use of exit statements.
<?php

$filename = 'sample.txt' ;
$file = fopen($filename, 'r') // open file for reading
or exit("unable to open file ($filename)");
?>

PHP function :
A function is a block of statements that can be used repeatedly in a program.A function will
not execute automatically when a page loads.A function will be executed by a call to function

A function is a block of code written in a program to perform some specific task. We can
relate functions in programs to employees in a office in real life for a better understanding of
how functions work. Suppose the boss wants his employee to calculate the annual budget.
So how will this process complete? The employee will take information about the statics from
the boss, performs calculations and calculate the budget and shows the result to his boss.
Functions works in a similar manner. They take informations as parameter, executes a block
of statements or perform operations on this parameters and returns the result.
PHP provides us with two major types of functions:

Built-in functions : PHP provides us with huge collection of built-in library functions. These
functions are already coded and stored in form of functions. To use those we just need to call
them as per our requirement like, var_dump, fopen(), print_r(), gettype() and so on.

User Defined Functions : Apart from the built-in functions, PHP allows us to create our own
customised functions called the user-defined functions.
Using this we can create our own packages of code and use it wherever necessary by
simply calling it.

Why should we use functions?


● Reusability: If we have a common code that we would like to use at various parts of a
program, we can simply contain it within a function and call it whenever required.
This reduces the time and effort of repetition of a single code. This can be done both
within a program and also by importing the PHP file, containing the function, in some
other program
● Easier error detection: Since, our code is divided into functions, we can easily detect
in which function, the error could lie and fix them fast and easily.
● Easily maintained: As we have used functions in our program, so if anything or any
line of code needs to be changed, we can easily change it inside the function and the
change will be reflected everywhere, where the function is called. Hence, easy to
maintain.

Creating a Function

While creating a user defined function we need to keep few things in mind:
Any name ending with an open and closed parenthesis is a function.
A function name always begins with the keyword function.
To call a function we just need to write its name followed by the parenthesis
A function name cannot start with a number. It can start with an alphabet or underscore.
A function name is not case-sensitive

Syntax:
function function_name()
{
executable code;
}

Example:
<?php
function helloworld()
{
echo "this is world ";
}
helloworld(); // Calling the function
?>

Output: this is world

PHP function with arguments


A function in PHP can be defined to accept input from calling environment/script in the form
of arguments. These arguments are given as comma separeted list inside the parentheses
in front of name of function. Note that while calling a function, same number of arguments
must be passed to it.

PHP supports calling a function by passing value, reference, arguments with default value
and by passing variable number of arguments.

function with arguments


In following example, a function is defined with two formal arguments. When this function is
called by passing the arguments by value. Arguments of function become its local variables.
Hence, any change in value of argument inside a function doesn't reflect outside it.

Here, value of $x is changed inside the function, but if we check its value after call to
function, it has not changed

Example
Live Demo

<?php
function add($x, $y){
$x= $x+$y ;
echo $x . "\n";
}
$x=10;
$y=20;
add($x,$y);
//outside function $x has previous value.
echo $x;
?>

Output
This will produce following result. −
30
10

Setting Default Values for Function parameter

PHP allows us to set default argument values for function parameters. If we do not pass any
argument for a parameter with default value then PHP will use the default set value for this
parameter in the function call.
Example:

<?php
// function with default parameter
function defGeek($str, $num=12)
{
echo "$str is $num years old \n";
}
// Calling the function
defGeek("Ram", 15);
// In this call, the default value 12
// will be considered
defGeek("Adam");
?>

Output:

Ram is 15 years old


Adam is 12 years old

In the above example, the parameter $num has a default value 12, if we do not pass any
value for this parameter in a function call then this default value 12 will be considered. Also
the parameter $str has no default value , so it is compulsory.

Returning Values from Functions

Functions can also return values to the part of program from where it is called. The return
keyword is used to return value back to the part of program, from where it was called. The
returning value may be of any type including the arrays and objects. The return statement
also marks the end of the function and stops the execution after that and returns the value.
Example:

<?php
// function along with three parameters
function proGeek($num1, $num2, $num3)
{
$product = $num1 * $num2 * $num3;
return $product; //returning the product
}
// storing the returned value
$retValue = proGeek(2, 3, 5);
echo "The product is $retValue";
?>

Output:
The product is 30

Parameter passing to Functions

PHP allows us two ways in which an argument can be passed into a function:

Pass by Value: On passing arguments using pass by value, the value of the argument gets
changed within a function, but the original value outside the function remains unchanged.
That means a duplicate of the original value is passed as an argument.
Pass by Reference: On passing arguments as pass by reference, the original value is
passed. Therefore, the original value gets altered. In pass by reference we actually pass the
address of the value, where it is stored using ampersand sign(&).

PHP Call By Value


PHP allows you to call function by value and reference both. In case of PHP call by value,
actual value is not modified if it is modified inside the function.

Let's understand the concept of call by value by the help of examples.

Example 1
In this example, variable $str is passed to the adder function where it is concatenated with
'Call By Value' string. But, printing $str variable results 'Hello' only. It is because changes are
done in the local variable $str2 only. It doesn't reflect to $str variable.

<?php
function adder($str2)
{
$str2 .= 'Call By Value';
}
$str = 'Hello ';
adder($str);
echo $str;
?>

Output:
Hello

Example 2
Let's understand PHP call by value concept through another example.

<?php
function increment($i)
{
$i++;
}
$i = 10;
increment($i);
echo $i;
?>

Output:

10

PHP Call By Reference


In case of PHP call by reference, actual value is modified if it is modified inside the function.
In such case, you need to use & (ampersand) symbol with formal arguments. The &
represents reference of the variable.

Let's understand the concept of call by reference by the help of examples.

Example 1
In this example, variable $str is passed to the adder function where it is concatenated with
'Call By Reference' string. Here, printing $str variable results 'This is Call By Reference'. It is
because changes are done in the actual variable $str.

<?php
function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
$str = 'This is ';
adder($str);
echo $str;
?>
Output:

This is Call By Reference

Example 2

Let's understand PHP call by reference concept through another example.

<?php
function increment(&$i)
{
$i++;
}
$i = 10;
increment($i);
echo $i;
?>

Output:

11

PHP Functions Scope


Variables declared outside of functions and classes are global. global variables are available
else where in the script.

Function variables are self-contained and do not affect variables in the main script.

Variables from the main script are not implicitly made available inside functions.

Example
Take a look at this example:

<?PHP
function foo() {
$bar = "java2s.com";
}
$bar = "PHP";
foo();
print $bar;
?>
The code above generates the following result.

Execution of the script starts at the $bar = "PHP" line, and then calls the foo() function.

foo() sets $bar to java2s.com, then returns control to the main script where $bar is printed
out.

Function foo() is called, and, having no knowledge that a $bar variable exists in the global
scope, creates a $bar variable in its local scope.

Once the function ends, all local scopes are gone, leaving the original $bar variable intact.

PHP Global Variables


A global variable can be accessed anywhere in your script, whether inside or outside a
function.

In PHP, all variables created outside a function are, in a sense, global in that they can be
accessed by any other code in the script that's not inside a function.

To use such a variable inside a function, write the word global followed by the variable name
inside the function ' s code block.

<?PHP//from w ww.j av a 2 s. c o m
$myGlobal = "Hello there!";

function hello() {
global $myGlobal;
echo "$myGlobal\n";
}

hello(); // Displays "Hello there!"


?>
The code above generates the following result.

hello() function accesses the $myGlobal variable by declaring it to be global using the global
statement. The function can then use the variable to display the greeting.

Example 1
We don't need to have created a variable outside a function to use it as a global variable.
Take a look at the following script:

<?PHP//w ww. j a v a2 s.c o m


function setup() {
global $myGlobal;
$myGlobal = "Hello there!";
}

function hello() {
global $myGlobal;
echo "$myGlobal\n";
}

setup();
hello(); // Displays "Hello there!"
?>
The code above generates the following result.

In this script, the setup() function is called first. It declares the $myGlobal variable as global,
and gives it a value.

Then the hello() function is called. It too declares $myGlobal to be global, which means it
can now access its value previously set by setup() and display it.

String manipulation :PHP String


PHP string is a sequence of characters i.e., used to store and manipulate text. PHP supports
only 256-character set and so that it does not offer native Unicode support. There are 4
ways to specify a string literal in PHP.

single quoted
double quoted
heredoc syntax
newdoc syntax (since PHP 5.3)

Single Quoted

We can create a string in PHP by enclosing the text in a single-quote. It is the easiest way to
specify string in PHP.

For specifying a literal single quote, escape it with a backslash (\) and to specify a literal
backslash (\) use double backslash (\\). All the other instances with backslash such as \r or
\n, will be output same as they specified instead of having any special meaning.

For Example

Following some examples are given to understand the single quoted PHP String in a better
way:
Example 1

<?php
$str='Hello text within single quote';
echo $str;
?>
Output:

Hello text within single quote


We can store multiple line text, special characters, and escape sequences in a single-quoted
PHP string.

Example 2

<?php
$str1='Hello text
multiple line
text within single quoted string';
$str2='Using double "quote" directly inside single quoted string';
$str3='Using escape sequences \n in single quoted string';
echo "$str1 <br/> $str2 <br/> $str3";
?>
Output:

Hello text multiple line text within single quoted string


Using double "quote" directly inside single quoted string
Using escape sequences \n in single quoted string
Example 3

<?php
$num1=10;
$str1='trying variable $num1';
$str2='trying backslash n and backslash t inside single quoted string \n \t';
$str3='Using single quote \'my quote\' and \\backslash';
echo "$str1 <br/> $str2 <br/> $str3";
?>
Output:

trying variable $num1


trying backslash n and backslash t inside single quoted string \n \t
Using single quote 'my quote' and \backslash
Note: In single quoted PHP strings, most escape sequences and variables will not be
interpreted. But, we can use single quote through \' and backslash through \\ inside single
quoted PHP strings.
Double Quoted

In PHP, we can specify string through enclosing text within double quote also. But escape
sequences and variables will be interpreted using double quote PHP strings.

Example 1

<?php
$str="Hello text within double quote";
echo $str;
?>

Output:

Hello text within double quote


Now, you can't use double quote directly inside double quoted string.

Example 2

<?php
$str1="Using double "quote" directly inside double quoted string";
echo $str1;
?>
Output:

Parse error: syntax error, unexpected 'quote' (T_STRING) in C:\wamp\www\string1.php on


line 2
We can store multiple line text, special characters and escape sequences in a double quoted
PHP string.

Example 3

<?php
$str1="Hello text
multiple line
text within double quoted string";
$str2="Using double \"quote\" with backslash inside double quoted string";
$str3="Using escape sequences \n in double quoted string";
echo "$str1 <br/> $str2 <br/> $str3";
?>
Output:

Hello text multiple line text within double quoted string


Using double "quote" with backslash inside double quoted string
Using escape sequences in double quoted string
In double quoted strings, variable will be interpreted.

Example 4

<?php
$num1=10;
echo "Number is: $num1";
?>

Output:

Number is: 10

Heredoc
Heredoc syntax (<<<) is the third way to delimit strings. In Heredoc syntax, an identifier is
provided after this heredoc <<< operator, and immediately a new line is started to write any
text. To close the quotation, the string follows itself and then again that same identifier is
provided. That closing identifier must begin from the new line without any whitespace or tab.

Naming Rules
The identifier should follow the naming rule that it must contain only alphanumeric characters
and underscores, and must start with an underscore or a non-digit character.

For Example

Valid Example

<?php
$str = <<<Demo
It is a valid example
Demo; //Valid code as whitespace or tab is not valid before closing identifier
echo $str;
?>
Output:

It is a valid example
Invalid Example

We cannot use any whitespace or tab before and after the identifier and semicolon, which
means identifier must not be indented. The identifier must begin from the new line.

<?php
$str = <<<Demo
It is Invalid example
Demo; //Invalid code as whitespace or tab is not valid before closing identifier
echo $str;
?>

This code will generate an error.

Output:

Parse error: syntax error, unexpected end of file in


C:\xampp\htdocs\xampp\PMA\heredoc.php on line 7
Heredoc is similar to the double-quoted string, without the double quote, means that quote in
a heredoc are not required. It can also print the variable's value.

Example

<?php
$city = 'Delhi';
$str = <<<DEMO
Hello! My name is Misthi, and I live in $city.
DEMO;
echo $str;
?>
Output:

Hello! My name is Misthi, and I live in Delhi.


Example

We can add multiple lines of text here between heredoc syntax.

<?php
$str = <<<DEMO
It is the example
of multiple
lines of text.
DEMO;
echo $str;

echo '</br>';

echo <<<DEMO // Here we are not storing string content in variable str.
It is the example
of multiple
lines of text.
DEMO;
?>
Output:

It is the example of multiple lines of text.


It is the example of multiple lines of text.
Below are the example with class and their variable

Example

<?php
class heredocExample{
var $demo;
var $example;
function __construct()
{
$this->demo = 'DEMO';
$this->example = array('Example1', 'Example2', 'Example3');
}
}
$heredocExample = new heredocExample();
$name = 'Gunjan';

echo <<<ECO
My name is "$name". I am printing some $heredocExample->demo example.
Now, I am printing {$heredocExample->example[1]}.
It will print a capital 'A': \x41
ECO;
?>
Output:

My name is "Gunjan". I am printing some DEMO example.


Now, I am printing Example2.
It will print a capital 'A': A

Newdoc
Newdoc is similar to the heredoc, but in newdoc parsing is not done. It is also identified with
three less than symbols <<< followed by an identifier. But here identifier is enclosed in
single-quote, e.g. <<<'EXP'. Newdoc follows the same rule as heredocs.

The difference between newdoc and heredoc is that - Newdoc is a single-quoted string
whereas heredoc is a double-quoted string.

Note: Newdoc works as single quotes.


Example-1:

<?php
$str = <<<'DEMO'
Welcome to javaTpoint.
Learn with newdoc example.
DEMO;
echo $str;
echo '</br>';
echo <<< 'Demo' // Here we are not storing string content in variable str.
Welcome to javaTpoint.
Learn with newdoc example.
Demo;
?>
Output:

Welcome to javaTpoint. Learn with newdoc example.


Welcome to javaTpoint. Learn with newdoc example.
Go to view page source and see the source of the program.

PHP String
Example

The below example shows that newdoc does not print the variable's value.

<?php
class heredocExample{
var $demo;
var $example;
function __construct()
{
$this->demo = 'DEMO';
$this->example = array('Example1', 'Example2', 'Example3');
}
}
$heredocExample = new heredocExample();
$name = 'Gunjan';

echo <<<ECO
My name is "$name". I am printing some $heredocExample->demo example.
Now, I am printing {$heredocExample->example[1]}.
It will print a capital 'A': \x41
ECO;
?>
Output:

The output of the above program will be like:

My name is "$name". I am printing some $heredocExample->demo example.


Now, I am printing {$heredocExample->example[1]}.
It will print a capital 'A': \x41
Note: newdoc supported by PHP 5.3.0+ versions.
Invalid Example
We cannot use any whitespace or tab before and after the identifier and semicolon, means
identifier must not be indented. The identifier must begin from the new line. It is also invalid
in newdoc same as heredoc.

<?php
$str = <<<'Demo'
It is Invalid example
Demo; //Invalid code as whitespace or tab is not valid before closing identifier
echo $str;
?>
This code will generate an error.

Output:

Parse error: syntax error, unexpected end of file in


C:\xampp\htdocs\xampp\PMA\newdoc.php on line 7

String related library functions /string functions


Manipulating PHP Strings
PHP provides many built-in functions for manipulating strings like calculating the length of a
string, find substrings or characters, replacing part of a string with different characters, take a
string apart, and many others. Here are the examples of some of these functions.

Searching
strpos() - Search For a Text Within a String
The PHP strpos() function searches for a specific text within a string. If a match is found, the
function returns the character position of the first match. If no match is found, it will return
FALSE.

Example
Search for the text "world" in the string "Hello world!":

<?php
echo strpos("Hello world!", "world");
// outputs 6
?>

Replacing
str_replace() - Replace Text Within a String
The PHP str_replace() function replaces some characters with some other characters in a
string.

Example
Replace the text "world" with "Dolly":

<?php
echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly!
?>
strlen() - Return the Length of a String
The PHP strlen() function returns the length of a string.
Example
Return the length of the string "Hello world!":
<?php
echo strlen("Hello world!"); // outputs 12
?>

str_word_count() - Count Words in a String


The PHP str_word_count() function counts the number of words in a string.
Example
Count the number of word in the string "Hello world!":
<?php
echo str_word_count("Hello world!"); // outputs 2
?>

strrev() - Reverse a String


The PHP strrev() function reverses a string.
Example
Reverse the string "Hello world!":
<?php
echo strrev("Hello world!"); // outputs !dlrow olleH
?>

PHP join() Function


Definition and Usage
The join() function returns a string from the elements of an array.
The join() function is built-in function in PHP and is used to join an array of elements which
are separated by a string.

Syntax

string join( $separator, $array)


Parameter: The join() function accepts two parameter out of which one is optional and one is
mandatory.

$separator : This is an optional parameter and is of string type. The values of the array will
be join to form a string and will be separated by the $separator parameter provided here.
This is optional, if not provided the default is “” (i.e. an empty string)
$array : The array whose value is to be joined to form a string.
Return Type: The return type of join() function is string. It will return the joined string formed
from the elements of $array.

Examples:
Input : join(array('Geeks','for','Geeks')
Output : GeeksforGeeks

Input : join("-",array('Geeks','for','Geeks')
Output : Geeks-for-Geeks

The join() function is an alias of the implode() function.

Note: The join() function accept its parameters in either order. However, for consistency with
explode(), you should use the documented order of arguments.

Note: The separator parameter of join() is optional. However, it is recommended to always


use two parameters for backwards compatibility.

Syntax
join(separator,array)
Parameter Values
Parameter Description
separator Optional. Specifies what to put between the array elements. Default is "" (an
empty string)
array Required. The array to join to a string
Example
Join array elements with a string:

<?php
$arr = array('Hello','World!','Beautiful','Day!');
echo join(" ",$arr);
?>

Example
Separate the array elements with different characters:

<?php
$arr = array('Hello','World!','Beautiful','Day!');
echo join(" ",$arr)."<br>";
echo join("+",$arr)."<br>";
echo join("-",$arr)."<br>";
echo join("X",$arr);
?>

Splitting string

PHP | explode() Function


explode() is a built in function in PHP used to split a string in different strings. The explode()
function splits a string based on a string delimeter, i.e. it splits the string wherever the
delimeter character occurs. This functions returns an array containing the strings formed by
splitting the original string.

Syntax :

array explode(separator, OriginalString, NoOfElements)


Parameters : The explode function accepts three parameters of which two are compulsory
and one is optional. All the three parameters are described below

separator : This character specifies the critical points or points at which the string will split,
i.e. whenever this character is found in the string it symbolizes end of one element of the
array and start of another.
OriginalString : The input string which is to be split in array.
NoOfElements : This is optional. It is used to specify the number of elements of the array.
This parameter can be any integer ( positive , negative or zero)
Positive (N): When this parameter is passed with a positive value it means that the array will
contain this number of elements. If the number of elements after separating with respect to
the separator emerges to be greater than this value the first N-1 elements remain the same
and the last element is the whole remaining string.
Negative (N):If negative value is passed as parameter then the last N element of the array
will be trimmed out and the remaining part of the array shall be returned as a single array.
Zero : If this parameter is Zero then the array returned will have only one element i.e. the
whole string.
When this parameter is not provided the array returned contains the total number of element
formed after separating the string with the separator.

Return Type: The return type of explode() function is array of strings.

Example
Break a string into an array:

<?php
$str = "Hello world. It's a beautiful day.";
print_r (explode(" ",$str));
?>

Examples:
<?php
$str = 'one,two,three,four';

// zero limit
print_r(explode(',',$str,0));

// positive limit
print_r(explode(',',$str,2));

// negative limit
print_r(explode(',',$str,-1));
?>

Regular expression :What is a Regular Expression?PHP | Regular Expressions


Regular expressions commonly known as a regex (regexes) are a sequence of characters
describing a special search pattern in the form of text string. They are basically used in
programming world algorithms for matching some loosely defined patterns to achieve some
relevant tasks. Some times regexes are understood as a mini programming language with a
pattern notation which allows the users to parse text strings. The exact sequence of
characters are unpredictable beforehand, so the regex helps in fetching the required strings
based on a pattern definition.

Regular Expression is a compact way of describing a string pattern that matches a particular
amount of text. As you know, PHP is an open-source language commonly used for website
creation, it provides regular expression functions as an important tool. Like PHP, many other
programming languages have their own implementation of regular expressions. This is the
same with other applications also, which have their own support of regexes having various
syntaxes. Many available modern languages and tools apply regexes on very large files and
strings. Let us look into some of the advantages and uses of regular expressions in our
applications.

Advantages and uses of Regular expressions:


In many scenarios, developers face problems whenever data are collected in free text fields
as most of the programming deals with data entries. Regular expressions are used almost
everywhere in today’s application programming.

Regular expressions help in validation of text strings which are of programmer’s interest.
It offers a powerful tool for analyzing, searching a pattern and modifying the text data.
It helps in searching specific string pattern and extracting matching results in a flexible
manner.
It helps in parsing text files looking for a defined sequence of characters for further analysis
or data manipulation.
With the help of in-built regexes functions, easy and simple solutions are provided for
identifying patterns.
It effectively saves a lot of development time, which are in search of specific string pattern.
It helps in important user information validations like email address, phone numbers and IP
address.
It helps in highlighting special keywords in a file based on search result or input.
It helps in identifying specific template tags and replacing those data with the actual data as
per the requirement.
Regexes are very useful for creation of HTML template system recognizing tags.
Regexes are mostly used for browser detection, spam filteration, checking password
strength and form validations.
We cannot cover everything under this topic, but let us look into some of the major regular
expression concepts. The following table shows some regular expressions and the
corresponding string which matches the regular expression pattern.
A regular expression is a sequence of characters that forms a search pattern. When you
search for data in a text, you can use this search pattern to describe what you are searching
for.

A regular expression can be a single character, or a more complicated pattern.

Regular expressions can be used to perform all types of text search and text replace
operations.

Syntax
In PHP, regular expressions are strings composed of delimiters, a pattern and optional
modifiers.

$exp = "/w3schools/i";
In the example above, / is the delimiter, w3schools is the pattern that is being searched for,
and i is a modifier that makes the search case-insensitive.

The delimiter can be any character that is not a letter, number, backslash or space. The most
common delimiter is the forward slash (/), but when your pattern contains forward slashes it
is convenient to choose other delimiters such as # or ~.

Regular Expression Functions


PHP provides a variety of functions that allow you to use regular expressions. The
preg_match(), preg_match_all() and preg_replace() functions are some of the most
commonly used ones:

Function Description
preg_match() Returns 1 if the pattern was found in the string and 0 if not
preg_match_all() Returns the number of times the pattern was found in the string, which
may also be 0
preg_replace() Returns a new string where matched patterns have been replaced
with another string

Using preg_match()
The preg_match() function will tell you whether a string contains matches of a pattern.

Example
Use a regular expression to do a case-insensitive search for "w3schools" in a string:

<?php
$str = "Visit W3Schools";
$pattern = "/w3schools/i";
echo preg_match($pattern, $str); // Outputs 1
?>

Using preg_match_all()
The preg_match_all() function will tell you how many matches were found for a pattern in a
string.

Example
Use a regular expression to do a case-insensitive count of the number of occurrences of
"ain" in a string:

<?php
$str = "The rain in SPAIN falls mainly on the plains.";
$pattern = "/ain/i";
echo preg_match_all($pattern, $str); // Outputs 4
?>

Using preg_replace()
The preg_replace() function will replace all of the matches of the pattern in a string with
another string.

Example
Use a case-insensitive regular expression to replace Microsoft with W3Schools in a string:

<?php
$str = "Visit Microsoft!";
$pattern = "/microsoft/i";
echo preg_replace($pattern, "W3Schools", $str); // Outputs "Visit W3Schools!"
?>

PHP preg_split() Function

Example
Use preg_split() to split a date into its components:

<?php
$date = "1970-01-01 00:00:00";
$pattern = "/[-\s:]/";
$components = preg_split($pattern, $date);
print_r($components);
?>
Definition and Usage
The preg_split() function breaks a string into an array using matches of a regular expression
as separators.

Syntax
preg_split(pattern, string, limit, flags)
Parameter Values
Parameter Description
pattern Required. A regular expression determining what to use as a separator
string Required. The string that is being split
limit Optional. Defaults to -1, meaning unlimited. Limits the number of elements that the
returned array can have. If the limit is reached before all of the separators have been found,
the rest of the string will be put into the last element of the array
flags Optional. These flags provide options to change the returned array:
PREG_SPLIT_NO_EMPTY - Empty strings will be removed from the returned array.
PREG_SPLIT_DELIM_CAPTURE - If the regular expression contains a group wrapped in
parentheses, matches of this group will be included in the returned array.
PREG_SPLIT_OFFSET_CAPTURE - Each element in the returned array will be an array
with two element, where the first element is the substring and the second element is the
position of the first character of the substring in the input string.

Array
| Arrays
Arrays in PHP is a type of data structure that allows us to store multiple elements of similar
data type under a single variable thereby saving us the effort of creating a different variable
for every data. The arrays are helpful to create a list of elements of similar types, which can
be accessed using their index or key. Suppose we want to store five names and print them
accordingly. This can be easily done by the use of five different string variables. But if
instead of five, the number rises to a hundred, then it would be really difficult for the user or
developer to create so many different variables. Here array comes into play and helps us to
store every element within a single variable and also allows easy access using an index or a
key. An array is created using an array() function in PHP.

There are basically three types of arrays in PHP:

Indexed or Numeric Arrays: An array with a numeric index where values are stored linearly.

Associative Arrays: An array with a string index where instead of linear storage, each value
can be assigned a specific key.

Multidimensional Arrays: An array which contains single or multiple array within it and can be
accessed via multiple indices.

Indexed or Numeric Arrays

These type of arrays can be used to store any type of elements, but an index is always a
number. By default, the index starts at zero. These arrays can be created in two different
ways as shown in the following example:

ExampleRun this code »


<?php
// Define an indexed array
$colors = array("Red", "Green", "Blue");
?>
Note: In an indexed or numeric array, the indexes are automatically assigned and start with
0, and the values can be any data type.

This is equivalent to the following example, in which indexes are assigned manually:

ExampleRun this code »


<?php
$colors[0] = "Red";
$colors[1] = "Green";
$colors[2] = "Blue";
?>
.
Associative Arrays

These types of arrays are similar to the indexed arrays but instead of linear storage, every
value can be assigned with a user-defined key of string type.
In an associative array, the keys assigned to values can be arbitrary and user defined
strings. In the following example the array uses keys instead of index numbers:

ExampleRun this code »


<?php
// Define an associative array
$ages = array("Peter"=>22, "Clark"=>32, "John"=>28);
?>
The following example is equivalent to the previous example, but shows a different way of
creating associative arrays:

ExampleRun this code »


<?php
$ages["Peter"] = "22";
$ages["Clark"] = "32";
$ages["John"] = "28";
?>

Multidimensional Arrays
The multidimensional array is an array in which each element can also be an array and each
element in the sub-array can be an array or further contain array within itself and so on. An
example of a multidimensional array will look something like this:

ExampleRun this code »


<?php
// Define a multidimensional array
$contacts = array(
array( "name" => "Peter Parker",
"email" => "peterparker@mail.com", ),
array(
"name" => "Clark Kent",
"email" => "clarkkent@mail.com",
),
array(
"name" => "Harry Potter",
"email" => "harrypotter@mail.com",
)
);
// Access nested value
echo "Peter Parker's Email-id is: " . $contacts[0]["email"];
?>

PHP Indexed Arrays


PHP Indexed Arrays
There are two ways to create indexed arrays:

The index can be assigned automatically (index always starts at 0), like this:

$cars = array("Volvo", "BMW", "Toyota");


or the index can be assigned manually:

$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
The following example creates an indexed array named $cars, assigns three elements to it,
and then prints a text containing the array values:

Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>

Loop Through an Indexed Array


To loop through and print all the values of an indexed array, you could use a for loop, like
this:

Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);

for($x = 0; $x < $arrlength; $x++) {


echo $cars[$x];
echo "<br>";
}
?>
Loop Through an Associative Array
To loop through and print all the values of an associative array, you could use a foreach loop,
like this:

Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

foreach($age as $x => $x_value) {


echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>

Iterate associative array using foreach loop in PHP


Given two arrays arr1 and arr2 of size n. The task is to iterate both arrays in the foreach
loop. Both arrays can combine into a single array using a foreach loop.

Array: Arrays in PHP is a type of data structure that allows to storing multiple elements of
similar data type under a single variable thereby saving the effort of creating a different
variable for every data. The arrays are helpful to create a list of elements of similar types,
which can be accessed by using their index or key.

Example:

Input : $sides = array('Up', 'Down', 'Left', 'Right')


$directions = array('North', 'South', 'West', 'East')

Output :
Up => North
Down => South
Left => West
Right => East
Example 1: This example uses foreach loop to display the elements of associative array.

<?php

// Declare an associative array using for each

$aso_arr = array(

"Up"=>"North",

"Down"=>"South",

"Left"=>"West",
"Right"=>"East"
);

// Use foreach loop to traverse each


// elements of array and display its
// key and value

foreach($aso_arr as $side=>$direc) {

echo $side . " => " . $direc . "\n";


}

?>
Output:

Up => North
Down => South
Left => West
Right => East

Example 2: This example uses array to display its index with value.

<?php

// Declare an array

$sides = array("Up", "Down", "Left", "Right");

// Use foreach loop to display the


// elements of array

foreach($sides as $index => $value) {

echo "sides[" . $index . "] => " . $value . " \n";


}

?>
Output:
sides[0] => Up
sides[1] => Down
sides[2] => Left
sides[3] => Right
Note: Every entry of the indexed array is similar to an associative array in which key is the
index number.
For example:

$sides = array("00"=>"Up", "01"=>"Down", "02"=>"Left", "03"=>"Right");


$directions = array("00"=>"North", "01"=>"South", "02"=>"West", "03"=>"East");
Since the index are common in all indexed arrays so it can use these indexes to access the
value in other arrays.

Example 3:

<?php

// Declare and initialize array

$sides = array("Up", "Down", "Left", "Right");

$directions = array("North", "South", "West", "East");

// Use foreach loop to display array elements

foreach( $sides as $index => $side ) {

echo $side . " => " . $directions[$index] . " \n";


}

?>
Output:
Up => North
Down => South
Left => West
Right => East

PHP | each() Function


The each() function is an inbuilt function in PHP and is used to get the current element
key-value pair of the given array to which the internal pointer is currently pointing. After
returning the key and value of the current element the internal pointer is incremented by one
in the array.

Note: You can use reset() function if you want to traverse the array again using each().

Syntax:

each($array)
Parameter: This function accepts a single parameter $array which is the input array in which
we want to find the current key-value pair to which the internal pointer is currently pointing.

Return Value: This function returns the key-value pair of the current element of the input
array $array. The key-value pair is returned in the form of a new array containing four
elements. The first two elements with keys(1 and Value) are for the current element’s value,
and next two elements with keys (0 and Key) are for the current element’s key. If the input
array is empty or if the internal pointer has reached the end of the array then this function
returns FALSE.

Examples:

Input : each(array('Ram', 'Shita', 'Geeta'))


Output :
Array
(
[1] => Ram
[value] => Ram
[0] => 0
[key] => 0
)
Explanation: Here input array contain many elements
but ram is the current element so the output contains
its key and value pair.
Below programs illustrate the each() function in PHP:

Program 1:

<?php

$arr = array('maya', 'Sham', 'Geet');

print_r (each($arr));

?>
Output:

Array
(
[1] => maya
[value] => maya
[0] => 0
[key] => 0
)
Program 2:

<?php

$arr = array('a' => 'anny', 'b' => 'bunny',

'c' => 'chinky');

reset($arr);

while (list($key, $val) = each($arr))

echo "$key => $val \n";

?>
Output:

a => anny
b => bunny
c => chinky

PHP String Functions

We have covered what are strings and how to create them in the last tutorial, now let's dive
deep into strings and learn about the in-built functions for string processing in PHP.

In general practice, using the right string function will save you a lot of time as they are
pre-defined in PHP libraries and all you have to do is call them to use them.

Commonly used PHP 5 String Functions


Below we have a list of some commonly used string functions in PHP:

strlen($str)
This function returns the length of the string or the number of characters in the string
including whitespaces.

<?php

$str = "Welcome to Studytonight";

// using strlen in echo method


echo "Length of the string is: ". strlen($str);

?>

Length of the string is: 23

str_word_count($str)
This function returns the number of words in the string. This function comes in handly in form
field validation for some simple validations.

<?php

$str = "Welcome to Studytonight";

// using str_word_count in echo method


echo "Number of words in the string are: ". str_word_count($str);

?>

Number of words in the string are: 3

strrev($str)
This function is used to reverse a string.

Let's take an example and see,

<?php

$str = "Welcome to Studytonight";

// using strrev in echo method


echo "Reverse: ". strrev($str);

?>

Reverse: thginotydutS ot emocleW

strpos($str, $text)
This function is used to find the position of any text/word in a given string. Just like an array,
string also assign index value to the characters stored in it, starting from zero.
<?php

$str = "Welcome to Studytonight";

// using strpos in echo method


echo "Position of 'Studytonight' in string: ". strpos($str, 'Studytonight');

?>

Position of 'Studytonight' in string: 11

str_replace($replacethis, $replacewith, $str)


This function is used to replace a part of the string with some text. While using this function,
the first argument is the part of string that you want to replace, second argument is the new
text you want to include, and the last argument is the string variable itself.

Let's take an example,

<?php

$str = str_replace("Studytonight", "Studytonight.com", "Welcome to Studytonight");

echo $str;

?>

Welcome to Studytonight.com

ucwords($str)
This function is used for formatting the string. This function converts first letter/character of
every word in the string to uppercase.

Let's take an example and see,

<?php

$str = "welcome to studytonight";

echo ucwords($str);

?>

Welcome To Studytonight

strtoupper($str)
To convert every letter/character of every word of the string to uppercase, one can use
strtoupper() method.

<?php

$str = "welcome to studytonight";

echo strtoupper($str);

?>

WELCOME TO STUDYTONIGHT

strtolower($str)
This function is used to convert every letter/character of a string to lowercase.

<?php

$str = "WELCOME TO STUDYTONIGHT";

echo strtolower($str);

?>

welcome to studytonight

str_repeat($str, $counter)
This function is used to repeat a string a given number of times. The first argument is the
string and the second argument is the number of times the string should be repeated.

<?php

$str = "Studytonight";

echo str_repeat($str, 4);

?>

StudytonightStudytonightStudytonightStudytonight

strcmp($str1, $str2)
This function is used to compare two strings. The comparison is done alphabetically. If the
first string is greater than second string, the result will be greater than 0, if the first string is
equal to the second string, the result will be equal to 0 and if the second string is greater
than the first string, then the result will be less than 0.

<?php
$str1 = "Studytonight";
$str2 = "Studytonight.com";

// comparing str1 and str2


echo strcmp($str1, $str2);

// comparing str2 and str1


echo strcmp($str2, $str1);

// comparing str1 with str1


echo strcmp($str1, $str1);

?>

-4
4
0

substr($str, $start, $length)


This function is used to take out a part of the string(substring), starting from a particular
position, of a particular length.

The first argument is the string itself, second argument is the starting index of the substring
to be exracted and the third argument is the length of the substring to be extracted.

<?php

$str = "Welcome to Studytonight";

echo substr($str, 11, 12);

?>

Studytonight

trim($str, charlist)
This function is used to remove extra whitespaces from beginning and the end of a string.
The second argument charlist is optional. We can provide a list of character, just like a string,
as the second argument, to trim/remove those characters from the main string.

<?php

$str1 = " Hello World ";

echo trim($str1) . "<br/>";

$str2 = "Hello Hello";


echo trim($str2,"Heo");

?>

Hello World
llo Hell

As you can see in the output, additional spaces from the beginning and end are removed
and in the second case, the characters specified are removed from the beginning and the
end of the string.

explode(separator, $str, $limit)


This function is used to break a string, create an array of the broken parts of the string and
return the array. The first argument, separator defines where to break the string from. It can
be a space, hiphen(-) or any other character.

The second argument of this function is the string itself and the third argument is the limit,
which specifies the number of array elements to return. the third argument is optional.

Let's have an example,

<?php

$str = "Its a beautiful day";

// we can directly print the result of explode


print_r(explode(" ", $str));

?>
Array (
[0] => Its
[1] => a
[2] => beautiful
[3] => day
)

In the example above, we have provided space as separator to break the string and return
an array.

If we provide the third argument limit as well, we can limit the number of array elements
returned. For example, if we provide 2 as the third argument, then we will only get 2
elements in the array, the first two.

implode(separator, $arr)
This function is used to form a string using the array elements from the array provided and
join them using the separator.

Let's take an example,


<?php

$arr = array("Its", "a", "beautiful", "day");

// <br> is used to jump to next line


echo implode(" ", $arr) . "<br>";
echo implode("-", $arr) . "<br>";
echo implode("/", $arr) . "<br>";

?>

Its a beautiful day


Its-a-beautiful-day
Its/a/beautiful/day

nl2br($str)
This function is used to change line break or \n to the HTML tag for line break, which is <br>.

This function is very useful to format string data to display on HTML pages because when a
multiline form data is submitted, it has \n included in the strnig for line breaks, but when you
display it on your HTML page, the line breaks will not get rendered because HTML doesn't
understand \n.

<?php

echo nl2br("Its a\nbeautiful day");

?>

Its a
beautiful day

Most Popular PHP String Functions


1. substr()
The substr() function helps you to access a substring between given start and end points of
a string. It can be useful when you need to get at parts of fixed format strings.

The substr() function prototype is as follows:

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


PHP
The return value is a substring copied from within string.

$blog = 'Your Blog is Excellent!';


PHP
When you call the function with a positive number for start (only), you will get the string from
the start position to the end of the string.

$blog = 'Your Blog is Excellent!';


substr($blog, 1);
// returns 'our Blog is Excellent!'
PHP
String position starts from 0, just like arrays.

When you call substr() with a negative start (only), you will get the string from the end of the
string minus start characters to the end of the string.

$blog = 'Your Blog is Excellent!';


substr($blog, -9);
// returns 'xcellent!'
PHP
The length parameter can be used to specify either a number of characters to return if it is
positive, or the end character of the return sequence if it is negative.

$blog = 'Your Blog is Excellent!';


substr($blog, 0, 4);
// returns 'Your'

substr($blog, 5, -13);
//returns 'Blog'
PHP
5 signifies the starting character point (B) and -13 determines the ending point (count 13
places backwards starting from the end of the string).

Learn more about substr() at http://us3.php.net/substr

2. strlen()
Next up we have the popular strlen() function for checking the length of a string. If you pass
it a string, strlen() will return its length.

echo strlen("Super Cali Fragilistics Expy Ali Docious");


// 40
PHP
Often times this function is used for validating input data or making sure a string variable has
a value.

<?php
$super = 'duper';

if (strlen ( $super ) > 0) {


echo 'Thanks for giving super some duper';
} else {
echo 'That might not have worked';
}
?>
// Thanks for giving super some duper
PHP
Learn more about strlen() at http://us3.php.net/strlen

3. str_replace()
Find and replace functionality is super useful with strings. You can use find and replace for
almost anything your imagination can think of.

The most commonly used string function for replacement is str_replace(). It has the following
prototype:

mixed str_replace(mixed needle, mixed new_needle, mixed haystack[, int &count]));


PHP
str_replace() replaces all the instances of needle in haystack with new_needle and returns
the new version of the haystack.The optional fourth parameter contains the number of
replacements made.

A really awesome feature of str_replace() is the ability to pass an array to both the search
terms and replace terms, as well as an array of strings to apply the rules to!

<?php
$strings = array (
'You like to have a fun time',
'You are a really nice person',
'Would you like to have a cup of coffee?'
);

$search = array (
'fun',
'time',
'person',
'coffee'
);
$replace = array (
'excellent',
'adventure',
'individual',
'joe'
);

$replaced = str_replace ( $search, $replace, $strings );

print_r ( $replaced );

/////////////////////////////////
Array
(
[0] => You like to have a excellent adventure
[1] => You are a really nice individual
[2] => Would you like to have a cup of joe?
)
?>
PHP
Learn more about str_replace() at http://php.net/manual/en/function.str-replace.php

4. trim()
The first step in tidying up data is to trim any excess whitespace from the string. This is a
good idea to prepare for a database insert or string comparison.

The trim() function strips whitespace from the start and end of a string and returns the
resulting string. The characters it strips by default are newlines and carriage returns (n and
r), horizontal and vertical tabs (t and x0B), end-of-string characters (), and spaces. You can
also pass it a second parameter containing a list of characters to strip instead of this default
list. Depending on your particular purpose, you might like to use the ltrim() or rtrim()
functions instead which perform the same operation, but you choose which side of the string
to affect.

Here we remove some literal junk from the beginning and end of our string:

<?php
$trimit = 'junk awesome stuff junk';

$trimmed = trim ( $trimit, 'junk' );

print_r ( $trimmed );

// awesome stuff
?>
PHP
Learn more about trim() at http://us2.php.net/manual/en/function.trim.php

5. strpos()
The function strpos() operates in a similar fashion to strstr(), except, instead of returning a
substring, it returns the numerical position of a needle within a haystack.
The strpos() function has the following prototype:

int strpos(string haystack, string needle, int [offset] );


PHP
The integer returned is the position of the first occurrence of the needle within the haystack.
The first character is in position 0 just like arrays.

We can see by running the following code that our exclamation point is at position 13.

$awesome = "Super Awesome!";


echo strpos($awesome, "!");
// 13
PHP
This function accepts a single character as the needle, but it can accept a string of any
length. The optional offset parameter determines the point within the haystack to start
searching.

$awesome = "Super Awesome!";


echo strpos($awesome, ‘m’, 3);
// 11
PHP
This code echoes the value 11 to the browser because PHP has started looking for the
character ‘m’ at position 3.

In any of these cases, if the needle is not in the string, strpos() will return false. To avoid
strange behavior you can use the === operator to test return values:

<?php
$awesome = "Super Awesome!";

$result = strpos ( $awesome, G );


if ($result === false) {
echo 'Not found';
} else {
echo 'Found at position ' . $result;
}

// Not found
?>
PHP
Learn more about strpos() at http://us2.php.net/strpos

6. strtolower()
Very often in PHP we need to compare strings or correct capitalization when people SHOUT
or do odd things. In order to compare strings, you want to make sure they are the same
case. We can use strtolower() for this purpose. We’ll use a function created with strtolower()
to calm down an angry person.

<?php
function calm_down($string) {

return strtolower ( $string );


}

$person = 'Angry people SHOUT!';

echo calm_down ( $person );


// angry people shout!
?>
PHP
Learn more about strtolower() at http://us3.php.net/strtolower

7. strtoupper()
strtoupper() is also quite popular for many of the reasons listed above, in reverse, meaning
take lowercase or a mixed case string and set it to all upper case. We’ll change things up
and create a wake up function to get our workers going in the morning.

<?php
function wake_up($string) {

return strtoupper ( $string );


}

$person = 'these people need to get working!';

echo wake_up ( $person );


// THESE PEOPLE NEED TO GET WORKING!
?>
PHP
Learn more about strtoupper() at http://us3.php.net/strtoupper

8. is_string()
is_string() is used to check if a value is a string. Let’s take a look at this within an if()
statement to take an action on strings in one way and non-strings in another. is_string()
returns true or false.

<?php
if (is_string ( 7 )) {
echo "Yes";
} else {
echo "No";
}
// No

if (is_string ( "Lucky Number 7" )) {


echo "Yes";
} else {
echo "No";
}
// Yes
?>
PHP
Learn more about is_string() at http://us2.php.net/is_string

9. strstr()
Last but not least we have the strstr() function. The function strstr() can be used to find a
string or character match within a longer string. This function can be used to find a string
inside a string, including finding a string containing only a single character.

The function prototype for strstr() is as follows:

string strstr(string haystack, string needle);


PHP
You pass strstr() a haystack to be searched and a needle to be found. If an exact match of
the needle is found, the strstr() function returns the haystack from the needle onward. If it
does not find the needle, it will return false. If the needle occurs more than once, the
returned string will begin from the first occurrence of the needle.

As an example, let’s say we have a submission form for people to submit their website, but
we would like it in a certain format. We can use strstr() to check for a string within a string to
help us here:

<?php
$url = 'vegibit.com';

if (strstr ( $url, 'https://www.' ) === false) {


$url = 'http://www.' . $url;
}

echo $url;
// https://www.vegibit.com
?>
By getting a mastery of these very commonly used string functions, you’ll be well on your
way to getting all kinds of tasks completed in your applications. If you enjoyed this tutorial,
you may also enjoy our JavaScript String Functions tutorial as well!

Concatenation of two strings in PHP


There are two string operators. The first is the concatenation operator (‘.‘), which returns the
concatenation of its right and left arguments. The second is the concatenating assignment
operator (‘.=‘), which appends the argument on the right side to the argument on the left
side.

Examples :

Input : string1: Hello


string2 : World!
Output : HelloWorld!

Input : string1: geeksfor


string2: geeks
Output : geeksforgeeks
Code #1:

<?php

// First String

$a = 'Hello';

// Second String

$b = 'World!';

// Concatenation Of String

$c = $a.$b;

// print Concatenate String

echo " $c \n";


?>
Output :

HelloWorld!
Code #2 :

<?php

// First String

$fname = 'John';

// Second String

$lname = 'Carter!';

// Concatenation Of String

$c = $fname." ".$lname;

// print Concatenate String

echo " $c \n";


?>
Output :

John Carter!

Code #3 :

<?php

// First String

$a = 'Hello';

// now $a contains "HelloWorld!"

$a. = "World!";

// Print The String $a

echo " $a \n";


?>
Output :

HelloWorld!

You might also like