math and string functions
math and string functions
<?php
?>
<?php
?>
<?php
echo strrev("Hello world!");
?>
The output of the code above will be: !dlrow olleH.
If a match is found, the function returns the character position of the first
match. If no match is found, it will return FALSE.
<?php
echo strpos("Hello world!", "world");
?>
<!DOCTYPE html>
<html>
<body>
<?php
echo str_replace("world", "Dolly", "Hello world!");
?>
</body>
</html>
<?php
?>
Output:World!
sensitive)
<?php
?>
No output
7.substr_count():The substr_count () function counts the number of
<?php
?>
Output:2
<?php
echo strtoupper("HelloWORLD!");
?>
Output:HELLO WORLD!
<?php
echo strtolower("HelloWORLD.");
?>
Output:
hello world.
<?php
echo ucfirst("helloworld!");
?>
Output:Hello world!
<?php
echo lcfirst("Helloworld!");
?>
Output:hello world!
12. ucwords():Converts the first character of each word in a string to
uppercase
<?php
echo ucwords("helloworld");
?>
Output:Hello World
Numeric functions:
1) Number_format:Used to formats a
numeric value using digit separators and
decimal points
<?php
echo
number_format(2509663);
?>
2) Rand():Used to generate a random
number.
<?php
echo rand();
?>
3) round():Round off a number with decimal
points to the nearest whole number.
<?php
echo round(3.49);
?>
3
4) sqrt():Returns the square root of a number
<?php
echo sqrt(100);
?>
10
5) cos(): Returns the cosine
<?php
echo cos(45);
?>
0.52532198881773
6) sin():Returns the sine
<?php
echo sin(45);
?>
0.85090352453412
7) tan():Returns the tangent
<?php
echo tan(45);
?>
1.6197751905439
8) pi(): Constant that returns the value of PI
<?php
echo pi();
?>
9) abs() : Return the absolute value of different numbers:
<?php
echo(abs(6.7) . "<br>");
echo(abs(-6.7) . "<br>");
echo(abs(-3) . "<br>");
?>
<?php
echo(floor(0.60) . "<br>");
echo(floor(0.40) . "<br>");
echo(floor(5) . "<br>");
?>
<?php
echo(pow(2,4) . "<br>");
echo(pow(-2,4) . "<br>");
echo(pow(-2,-4) . "<br>");
echo(pow(-2,-3.2));
?>
<?php
?>
<?php
?>
<?php
?>
<?php
What is an Array?
If you have a list of items (a list of car names, for example), storing the
cars in single variables could look like this:
$cars1 = "Volvo";
$cars2 = "BMW";
$cars3 = "Toyota";
However, what if you want to loop through the cars and find a specific
one? And what if you had not 3 cars, but 300?
An array can hold many values under a single name, and you can access
the values by referring to an index number.
array();
The index can be assigned automatically (index always starts at 0), like
this:
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
Associative arrays are arrays that use named keys that you assign to
them.
"Joe"=>"43");
or:
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
Example
<?php
>"43");
Example
<?php
>"43");
echo "<br>";
Array functions:
1. array_push() to insert an element into the array
<?php
$a=array("red","green");
array_push($a,"blue","yellow");
print_r($a);
?>
<?php
$a=array("a"=>"Volvo","b"=>"BMW","c"=>"Toyota";
print_r(array_reverse($a));
?>
output:
Array ( [c] => Toyota [b] => BMW [a] => Volvo )
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43","Harry"=>"50");
print_r(array_chunk($age,2,true));
?>
Output:
<?php
$fname=array("Peter","Ben","Joe");
$age=array("35","37","43");
$c=array_combine($fname,$age);
print_r($c);
?>
$a=array("A","Cat","Dog","A","Dog");
print_r(array_count_values($a));
?>
3. Output:
values only)
<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("e"=>"red","f"=>"green","g"=>"blue");
$result= array_diff($a1,$a2);
print_r($result);
?>
7. array_fill_keys:
<?php
$keys=array("a","b","c","d");
$a1=array_fill_keys($keys,"blue");
print_r($a1);
?>
Output:
Array ( [a] => blue [b] => blue [c] => blue [d] => blue )
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,2));
?>
output: Array ( [0] => blue [1] => yellow [2] => brown )
Start the slice from the third array element, and return the rest of the
elements in the array:
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,1,2));
?>
<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("a"=>"purple","b"=>"orange");
array_splice($a1,0,3,$a2);
print_r($a1);
?>
output: Array ( [0] => purple [1] => orange [c] => blue [d] => yellow )
<?php
$a = "Original";
extract($my_array);
?>
Output:
11. Array_pad($array, $size, $value)- Returns an array with $value added to the end of
$array until it contains $size elements. If $size is negative, the value is added to the
Eg: <?php
$a=array("red","green");
print_r(array_pad($a,5,"blue"));
?>
Output : Array ( [0] => red [1] => green [2] => blue [3] => blue [4] => blue )
more arrays in one array. String keys in $array2 overwrite string keys in $array1 but
Eg: <?php
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_merge($a1,$a2));
?>
Output : Array ( [0] => red [1] => green [2] => blue [3] => yellow )
Eg: <?php
$a1=array("a"=>"red","b"=>"green");
$a2=array("c"=>"blue","b"=>"yellow");
print_r(array_merge($a1,$a2));
?>
Output : Array ( [a] => red [b] => yellow [c] => blue )
Eg : <?php
$a=array(3=>"red",4=>"green");
print_r(array_merge($a));
?>
13.ARRAY STACK:
<?php
$numbers=array('a','b','c');
print_r($numbers);
print_r($numbers);
echo "<BR> The number popped out is $x<BR>The array after the pop operation is :";
print_r($numbers);
?>
OUTPUT:
The orginal array is :Array ( [0] => a [1] => b [2] => c )
The array after pushing 50 is : Array ( [0] => a [1] => b [2] => c [3] => 50 )
The array after the pop operation is :Array ( [0] => a [1] => b [2] => c )
14.ARRAY QUEUE:
<?php
$numbers=array('a','b','c');
print_r($numbers);
print_r($numbers);
print_r($numbers);
?>
OUTPUT
The orginal array is :Array ( [0] => a [1] => b [2] => c )
The array after the array_shift operation is :Array ( [0] => b [1] => c )
The array after using array_unshift is :Array ( [0] => z [1] => b [2] => c )
<?php
$a=array(5,15,25);
echo array_sum($a);Returns sum of the elements in the array
?>
OUTPUT : 45
<?php
$a=array(5,5,2,10);
echo(array_product($a));//Returns the product of the elements in array
?>
OUTPUT : 500
16.Searching in arrays
The in_array() function searches an array for a specific value.
Syntax :in_array(search,array,type)
If the search parameter is a string and the type parameter is set to TRUE, the search is
case-sensitive.
<?php
if (in_array("Glenn", $people))
else
?>
The array_key_exists() function checks an array for a specified key, and returns true if
the key exists and false if the key does not exist.
array_key_exists(key,array)
<?php
$a=array("Volvo"=>"XC90","BMW"=>"X5");
if (array_key_exists("Volvo",$a))
else
?>
Remember that if you skip the key when you specify an array, an integer key is
<?php
$a=array("Volvo","BMW");
if (array_key_exists(0,$a))
else
?>
The array_search() function search an array for a value and returns the key.
array_search(value,array,strict)
<?php
$a=array('a'=>123,'b'=>456,'c'=>789);
?>
OUTPUT :
The array_unique() function removes duplicate values from an array. If two or more array
values are the same, the first appearance will be kept and the other will be removed.
Syntax : array_unique(array,sorting_type)
<?php
$a=array("a"=>"red","b"=>"green","c"=>"red");
print_r(array_unique($a));
?>
to sort
The sort() function sorts an indexed array in ascending order and reindexes it.
Syntax : sort(array,sortingtype);
<?php
$cars=array("Volvo","BMW","Toyota");
$clength=count($cars);
for($x=0;$x<$clength;$x++)
echo $cars[$x];
echo "<br>";
sort($cars);
echo "The sorted array is : <BR>";
for($x=0;$x<$clength;$x++)
echo $cars[$x];
echo "<br>“; }
?>
OUTPUT:
The rsort() function sorts an indexed array in descending order and reindexes.
Syntax : rsort(array,sortingtype);
<?php
$numbers=array(4,6,2,22,11);
rsort($numbers);
$arrlength=count($numbers);
for($x=0;$x<$arrlength;$x++)
echo $numbers[$x];
echo "<br>";
?>
OUTPUT :
22
11
PHP understands multidimensional arrays that are two, three, four, five, or
more levels deep.
<?php
$cars = array
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold:
".$cars[1][2].".<br>";
".$cars[2][2].".<br>";
".$cars[3][2].".<br>";
?>
Besides the built-in PHP functions, we can create our own functions. A function is a block of
statements that can be used repeatedly in a program. A function is a piece of code which
takes one more input in the form of parameter and does some processing and returns a
value. There are two parts which should be clear to you −
Syntax:
function functionName() {
code to be executed;
}
Note: A function name can start with a letter or underscore (not a number). Function names
are NOT case-sensitive.
The opening curly brace ( { ) indicates the beginning of the function code and the closing
curly brace ( } ) indicates the end of the function.
Example:
<html>
<head>
<title>Writing PHP Function</title>
</head>
<body>
<?php
/* Defining a PHP Function */
function writeMessage() {
echo "You are really a nice person, Have a nice time!";
}
Following example takes two integer parameters and add them together and then print
them.
Example:
<html>
<head>
<title>Writing PHP Function with Parameters</title>
</head>
<body>
<?php
function addFunction($num1, $num2) //function
{
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20); // fun call
?>
</body>
</html>
Output:
Example
The following example has a function with two arguments ($fname and $year):
<!DOCTYPE html>
<html>
<body>
<?php
function familyName($fname, $year)
{
echo "$fname . Born in $year <br>";
}
familyName("Hege","1975");
familyName("Stale","1978");
familyName(“Jim","1983");
?>
</body>
</html>
Output:
You can return more than one value from a function using return array(1,2,3,4).
Following example takes two integer parameters and add them together and then returns
their sum to the calling program. Note that return keyword is used to return a value from a
function.
Example:
<html>
<head>
<title>Writing PHP Function which returns value</title>
</head>
<body>
<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);
echo "Returned value from the function : $return_value";
?>
</body>
</html>
Output:
Example
<!DOCTYPE html>
<html>
<body>
<?php
function sum($x, $y) {
$z = $x + $y;
return $z;
}
echo "5 + 10 = " . sum(5,10) . "<br>";
echo "7 + 13 = " . sum(7,13) . "<br>";
echo "2 + 4 = " . sum(2,4);
?>
</body>
</html>
Output:
5 + 10 = 15
7 + 13 = 20
2+4=6
Any changes made to an argument in these cases will change the value of the original
variable. You can pass an argument by reference by adding an ampersand to the variable
name in either the function call or the function definition.
Example:
<html>
<head>
<title>Passing Argument by Reference</title>
</head>
<body>
<?php
function addFive($num) {
$num += 5;
}
function addSix(&$num) {
$num += 6;
}
$orignum = 10;
addFive( $orignum );
echo "Original Value is $orignum<br />";
addSix( $orignum );
echo "Original Value is $orignum<br />";
$list = array(1,4,6,8);
array_fns($list, $s, $p, $a);
echo "Sum = $s, Product = $p, Average = $a";
?>
</body>
</html>
Output:
Original Value is 10
Original Value is 16
Sum = 19, Product = 192, Average = 4.75
Example
<!DOCTYPE html>
<html>
<body>
<?php
function setHeight($minheight = 50) {
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight();
setHeight(135);
setHeight(80);
?>
</body>
</html>
Output:
The height is : 350
The height is : 50
The height is : 135
The height is : 80
<a href="http://www.tutorialspoint.com/index.htm">Home</a> -
<a href="http://www.tutorialspoint.com/ebxml">ebXML</a> -
<a href="http://www.tutorialspoint.com/ajax">AJAX</a> -
<a href="http://www.tutorialspoint.com/perl">PERL</a> <br />
Now create as many pages as you like and include this file to create header. For example
now your test.php file can have following content.
<html>
<body>
vars.php
<?php
$color = 'green';
$fruit = 'apple';
?>
test.php
<?php
echo "A $color $fruit"; // A
include 'vars.php';
<html>
<body>
</body>
</html>