Professional Documents
Culture Documents
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
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
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
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
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
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:
<?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.
We will discuss about continue and break keywords used to control the loops execution.
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;
</body>
</html>
This will produce the following result −
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;
</body>
</html>
This will produce the following result −
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
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);
</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 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.
Live Demo
<html>
<body>
<?php
$i = 0;
</body>
</html>
This will produce the following result −
Loop stopped at i = 3
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.
Live Demo
<html>
<body>
<?php
$array = array( 1, 2, 3, 4, 5);
</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.
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
?>
PHP supports calling a function by passing value, reference, arguments with default value
and by passing variable number of arguments.
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
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:
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.
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
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(&).
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
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:
Example 2
<?php
function increment(&$i)
{
$i++;
}
$i = 10;
increment($i);
echo $i;
?>
Output:
11
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.
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() 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:
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.
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:
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:
<?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:
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:
Example 2
<?php
$str1="Using double "quote" directly inside double quoted string";
echo $str1;
?>
Output:
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:
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;
?>
Output:
Example
<?php
$city = 'Delhi';
$str = <<<DEMO
Hello! My name is Misthi, and I live in $city.
DEMO;
echo $str;
?>
Output:
<?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:
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:
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.
<?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:
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:
<?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:
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
?>
Syntax
$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
Note: The join() function accept its parameters in either order. However, for consistency with
explode(), you should use the documented order of arguments.
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
Syntax :
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.
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 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.
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.
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 ~.
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!"
?>
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.
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.
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:
This is equivalent to the following example, in which indexes are assigned manually:
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:
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:
The index can be assigned automatically (index always starts at 0), like this:
$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] . ".";
?>
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
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:
Output :
Up => North
Down => South
Left => West
Right => East
Example 1: This example uses foreach loop to display the elements of associative array.
<?php
$aso_arr = array(
"Up"=>"North",
"Down"=>"South",
"Left"=>"West",
"Right"=>"East"
);
foreach($aso_arr as $side=>$direc) {
?>
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
?>
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:
Example 3:
<?php
?>
Output:
Up => North
Down => South
Left => West
Right => East
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:
Program 1:
<?php
print_r (each($arr));
?>
Output:
Array
(
[1] => maya
[value] => maya
[0] => 0
[key] => 0
)
Program 2:
<?php
reset($arr);
?>
Output:
a => anny
b => bunny
c => chinky
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.
strlen($str)
This function returns the length of the string or the number of characters in the string
including whitespaces.
<?php
?>
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
?>
strrev($str)
This function is used to reverse a string.
<?php
?>
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
?>
<?php
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.
<?php
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
echo strtoupper($str);
?>
WELCOME TO STUDYTONIGHT
strtolower($str)
This function is used to convert every letter/character of a string to lowercase.
<?php
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";
?>
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";
?>
-4
4
0
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
?>
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
?>
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.
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.
<?php
?>
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.
?>
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
?>
Its a
beautiful day
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.
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).
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.
<?php
$super = 'duper';
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:
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'
);
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';
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:
We can see by running the following code that our exclamation point is at position 13.
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!";
// 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) {
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) {
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
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.
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';
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!
Examples :
<?php
// First String
$a = 'Hello';
// Second String
$b = 'World!';
// Concatenation Of String
$c = $a.$b;
HelloWorld!
Code #2 :
<?php
// First String
$fname = 'John';
// Second String
$lname = 'Carter!';
// Concatenation Of String
$c = $fname." ".$lname;
John Carter!
Code #3 :
<?php
// First String
$a = 'Hello';
$a. = "World!";
HelloWorld!