One thing which I like the most about the PHP is its inbuild/pre-defined functions.
If you are coming from C/C++ background. Then you will start loving the gift of PHP functions.
For Eg. array_sum() . you don’t have to write a logic for iterating through all the array and add their values.
PHP has a pre-defind function which do the same job for you.
1) explode() : it converts a string into array with the supplied character.
Syntax : explode($character,$arrayname,$noofparts) , here $noofparts is optional
Eg: suppose in language column we have stored “english,french,japanese”.
And we want to print all these language one by one , here we will use explode , its syntax will be
$langauge=”english,french,japanese”;
$langArray=explode(“,”,$langauge);
Now here $langArray[0]=english
$langArray[1]=french
$langArray[2]=japanese
we can print these value using foreach array like
foreach($langArray as $l){
echo $l.”<br/>”;
}
above will output all languages in each line
2) implode()
Implode does the reverse of the explode ie it converts the array into string.
Suppose we have a array called subjects with value
$subject[0]=”English”;
$subject[1]=”Math”;
$subject[2]=”Hindi”;
$subjecttext=implode(“,”,$subject);
now subject text will output
English,Math,Hindi
3) in_array()
This is very useful function when we want to test whether a values exist in array or not.
Syntax:
in_array($valuetosearchfor,$arrayinwhichseraching)
For eg.
If(in_array(“GK”,$subject)){
echo “Is there”;
}
else
echo “Not in the subject array”;
This will out put “Not in the array” since GK is not there in the subject array
Note: It work only for single dimensional array not for the Multi-dimensional array.
For Multi-dimensional array , we can use below code
foreach($subjects as $value)
{
if(in_array("GK", $value))
{
echo "GK is in the array";
}
}
4) count()
It returns the number of elements in the array.
$user[0]=”ramesh”;
$user[1]=”Gunn”;
echo count($user);
will output 2. ie the number of elements in the array
5) mt_rand()
This function is used to generate random numbers.This function is very useful when we want to generate a random number.
Syntax
mt_rand() , it will generate value between 0 to mt_getrandmax()
mt_rand($min,$max) , it will genarate value greater then $min and less then equal to $max value
if $max is less then $min it will generate an warning and will return false;
6) substr()
This function is used to extract some part of a string
Syntax
substr($string,$startingindex,$lastindex) .