Split a string and store into an array

This PHP script code is for split a string into the specified length and store it into an array. Here we are using a form to enter the string to split , length at which split process and the cut mode . In normal cut modes split wont happen in the middle of a single word , in strict mode split will happen strictly even in the middle of a single word.

<html>
<head>
</head>
<body>
<form name="split" action="" method="post">
Enter the string to Split
<input type="text" name="text1" /><br />
Enter the character length to split:<input type="text" name="len1" /><br />
Cut Mode;<select name="cut">
<option value=0 t>Normal Cut</option>
<option value=1>Strict Cut</option>
</select><br>
<input type="submit" value="split" name="btnsubmit" />

</form>
<?php
if(isset($_POST['btnsubmit']))
{
$text=$_POST['text1'];
$len1=$_POST['len1'];
$mode=$_POST['cut'];
//echo "Original String ".$text;
//$count= strlen($text);
$newtext = wordwrap($text, $len1, "<***>",$mode);
$result=explode('<***>', $newtext);
$count= count($result);
$i=0;
while ($i<$count)
{
echo "String ".$i." is : <b>".$result[$i]."</b><br>";
$i=$i+1;
}
}
?>
</body>
</html>

PHP wordwrap function

PHP wordwrap() function is used for wrapping a string to a given number of characters. It will cut the string at the specified length and insert the string or character we have entered at that position.

Its Syntax will be :
wordwrap ( string , length , break character , cut mode );

  • First parameter will be the string to be wrapped
  • Second parameter specifies at which length wrap should occur.
  • Third parameter specified the character or string to be inserted at the specified length.
  • Fourth parameter is optional. This cut mode parameter specified the mode of cutting. When we specify this parameter as TRUE , cutting will occur at the middle of words too , it will strictly cut at the specified length. By default its value will be false , and cutting wont happen in the middle of a word.

You will get more clear picture about this wordwrap function after seeing the following sample PHP programs and its output

<?php
$text="This tutorial will show about wordwrap function";
echo wordwrap($text,5," * ")
?>

Its output will be :

This * tutorial * will * show * about * wordwrap * function

Here we can see that single words are not splitted , they remains the same.

Now look at the next program with CUT mode parameter as TRUE

<?php
$text="This tutorial will show about wordwrap function";
echo wordwrap($text,5," * ", TRUE)
?>
Its output will be :

This * tutor * ial * will * show * about * wordw * rap * funct * ion

Here we can see that function has splitted the string strictly at the specified length and single words also splitted .

A Prime Number list generation PHP script

A prime number is defined as a number which can be only divisible by 1 and that number itself. That number cannot be divisible by any other number. So if we try to divide that number by any other number between one and that number , we will get a remainder. According to the prime number definition number one ( 1 ) wont consider as a primer number. The smallest primer number is 2 .

See is a list of primer number below 50
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47,

Here is a sample PHP script program to create a list of prime numbers
In this example we are going to print first 20 prime numbers.

<?php
$count = 0 ;
$number = 2 ;
while ($count < 20 )
{
$div_count=0;
for ( $i=1;$i<=$number;$i++)
{
if (($number%$i)==0)
{
$div_count++;
}
}
if ($div_count<3)
{
echo $number." , ";
$count=$count+1;
}
$number=$number+1;
}
?>

Its output will be :

2 , 3 , 5 , 7 , 11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 , 41 , 43 , 47 , 53 , 59 , 61 , 67 , 71 ,

Logic of this program : We need first store the current number to a variable. And then we will find the remainder for each division of other numbers with the stored number using a loop. And we will increment a counter if remainder found zero. After all the division operations with other numbers we will check the total counter for the remainder. If its value greater than two means , that number can be divisible by some other number instead of 1 and that number itself.If its value less than three means , its a primer number.

Now look at another PHP script for generating a list of prime numbers below 100.

<?php
$number = 2 ;
while ($number < 100 )
{
$div_count=0;
for ( $i=1;$i<=$number;$i++)
{
if (($number%$i)==0)
{
$div_count++;
}
}
if ($div_count<3)
{
echo $number." , ";
}
$number=$number+1;
}
?>

Its output will be ;

2 , 3 , 5 , 7 , 11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 , 41 , 43 , 47 , 53 , 59 , 61 , 67 , 71 , 73 , 79 , 83 , 89 , 97 ,

This not only the one method of logic to create Primer number series .. You can create the list other methods and loops in PHP.

PHP Fibonacci Series printing

A Fibonacci Series of numbers will look like
0 , 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 , 55

First two Fibonacci numbers are 0 and 1 . After that each number will be the sum of previous two numbers . Here we can see that third Fibonacci number is 1 ( sum of first two numbers 0 + 1 ) , and fourth Fibonacci number will be the sum of third and second number ( 1 + 1 = 2 ) , and fifth Fibonacci number will be the sum of fourth and third number ( 2 + 1 = 3 ). The series will go like that infinity .

Now we can learn how to make a Fibonacci series using PHP .
Here is the PHP script for printing first 20 Fibonacci numbers .

<?php
$count = 0 ;
$f1 = 0;
$f2 = 1;
echo $f1." , ";
echo $f2." , ";
while ($count < 20 )
{
$f3 = $f2 + $f1 ;
echo $f3." , ";
$f1 = $f2 ;
$f2 = $f3 ;
$count = $count + 1;
}
?>

Its output will be :

0 , 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 , 55 , 89 , 144 , 233 , 377 , 610 , 987 , 1597 , 2584 , 4181 , 6765 , 10946 ,

In this example I have created the series using a while loop .Like this we can make Fibonacci Series using for loops also in PHP .

PHP html_entity_decode – convert to characters

PHP html_entity_decode function is used for covert the HTML entities to its corresponding characters.This function can be used for decode the string maid by htmlentities function.

Its Syntax Will be :
html_entity_decode ( String , Quote Style, Character Set ) ;
First parameter is the string to be converted to characters
Second paramters is an optional will , which will specify how to deal with Single and double quotes
Available quote styles are
ENT_COMPAT Will convert double-quotes and leave single-quotes alone.
ENT_QUOTES Will convert both double and single quotes.
ENT_NOQUOTES Will leave both double and single quotes unconverted.

Third parameter is also optional, where we can specify the character set used in conversion

See a Sample PHP program using html_entity_decode function

<?php
$data="mysqlbrain's tutorials are very <b>good</b>";
$data_1 = htmlentities($data,ENT_QUOTES);
echo html_entity_decode($data_1);
echo "<br>";
echo html_entity_decode($data_1,ENT_QUOTES);
?>

Its output will be :

mysqlbrain’s tutorials are very good
mysqlbrain’s tutorials are very good

We can see that in html_entity_decode with ENT_QUOTES parameter convert the single quote html entity to character .

PHP htmlentities() – convert characters to html entities

PHP htmlentities function is used for covert the characters to its HTML entities. This function will automatically identify the characters which have an equivalent HTML entity , and then convert to it.

Its Synatx will be ;
htmlentities ( string , quote style , Character set );

First parametrer will be the string to convert
Second parameter is optional. Here we can specify how to deal with single quotes (‘) and double quotes (“)
Available quote styles are

  • ENT_COMPAT : Will convert double-quotes and leave single-quotes alone.
  • ENT_QUOTES : Will convert both double and single quotes.
  • ENT_NOQUOTES : Will leave both double and single quotes unconverted.

Third parameter is also optional , which defines the character set used in conversion. By default character set will be ISO-8859-1

Now look at some sample PHP programs using htmlentities function

<?php
$data="mysqlbrain's tutorials are very <b>good<b>";
echo htmlentities($data);
echo "<br>";
echo htmlentities($data,ENT_QUOTES)
?>

Now look at the source code of the ouput in browser , it will be

mysqlbrain’s tutorials are very <b>good<b>
mysqlbrain’s tutorials are very <b>good<b>

We can see that first htmlentities statement leaves the single quote , and second time it covert the single quote to html entity.

Its a good practise to use this function before storing the data to mysql tables. And we can use PHP html_entity_decode function to decode the string.

PHP search in array

In this tutorial we are going to learn how to search in array. In PHP we can use mainly two functions for this

  • in_array()
  • array_search()

PHP array search using in_array() function
This function will check the specified value is present in an array or not. It will return TRUE if the value is present in array, otherwise it will return FALSE
Its Syntax will be :
in_array(Value to search , array , strict Boolean);
First parameter will be the value to search in an array
Second parameter will the array to search
Third parameter is optional. If we specify it as TRUE function will check the type of value also. Type of the value should also match in the array value, then only it will return TRUE. By default this strict parameter will be FALSE ( wont check the type )
Now look at a sample PHP program using in_array search

<?php
$age = array("Syam"=>30, "Binu"=>25, "Bob"=>50, "cathy"=>30);
$key_search="25";
if (in_array($key_search,$age))
{
echo "VALUE EXIST without strict parameter search";
}
else
{
echo "VALUE NOT PRESENT without strict parameter search";
}
echo "<BR>";
if (in_array($key_search,$age,TRUE))
{
echo "VALUE EXIST with strict parameter search";
}
else
{
echo "VALUE NOT PRESENT with strict parameter search";
}
?>

Its output will be :

VALUE EXIST without strict parameter search
VALUE NOT PRESENT with strict parameter search

In this case we can see that without strict parameter function found the value in array. But when we used the strict parameter it will check the type also. Here we declared the value to search as a string , and in array the value is in type integer. So no match is there and the function will return FALSE.

PHP array search using array_search() function

This function will search for the specified value in an array and will return the corresponding key of the value if the search is successful.
Its syntax also similar to in_array:
array_search(Value to search , array , strict Boolean);

Now look at a sample PHP program using array_search function :

<?php
$age = array("Syam"=>30, "Binu"=>25, "Bob"=>50, "cathy"=>30);
$key_search="25";
if (array_search($key_search,$age))
{
echo "VALUE EXIST without strict parameter search and its key is ".array_search($key_search,$age);
}
else
{
echo "VALUE NOT PRESENT without strict parameter search";
}
echo "<BR>";
if (array_search($key_search,$age,TRUE))
{
echo "VALUE EXIST with strict parameter search and its key is ".array_search($key_search,$age,TRUE);
}
else
{
echo "VALUE NOT PRESENT with strict parameter search";
}
?>

Its output will be :

VALUE EXIST without strict parameter search and its key is Binu
VALUE NOT PRESENT with strict parameter search

Difference between these two functions:

  • array_search function will return the key or index
  • in_array function will return TRUE or false according to search match

PHP array_key_exists – checking a key exist in array

PHP array_key_exists function is used for checking a specified key or index exists in an array. It will return TRUE if the specified key exists in array or it will return FALSE if that key is not present in the array.Its using for a key search in an array. We don’t need to use loop through complete array and check each time with the key.Just need to use this function for this purpose.

Its Syntax will be :
array_key_exists function( Key value to search , array )

Now look at a sample PHP program with array_key_exists function for searching a key in array

<?php
$age = array("Syam"=>30, "Binu"=>25, "Bob"=>50, "cathy"=>30);
$key_search="Bob";
if (array_key_exists($key_search,$age))
{
echo "KEY EXISTS IN ARRAY";
}
else
{
echo "KEY CANNOT BE FOUND";
}
?>

Its output will be :

KEY EXISTS IN ARRAY

In this example our key is “Bob” and that key is there in the declared array. So our
array_key_exists() function will return TRUE in this example.

PHP mail() – send email

PHP mail() function is used for sending emails from your website.

Syntax of mail() function is :

  • mail (to email , Subject of email , email message , header , additional parameters );
  • Here First parameter will be the email address of the receiver
  • Second parameter will be the Subject ( title ) of your email
  • Third parameter will be the content of your email , you can use html tags and all for proper formatting
  • Third parameter is the header of your email, it will contain all the properties and setting for that email , sender email address also should specify in header , we can also add reply to address , format of email etc in header. Using detailed header is a good practice .

Sample of a header
$header = “From: from@gmail.comrnContent-type: text/htmlrnReply-To: from@gmail.com”;

In this header we have specified the from address, reply address and content type of the message.

Now look at a simple example of mail() function

<?php
$from="kssyam@gmail.com";
$to="to@gmail.com";
$subject="Test Mail";
$message="Hi ,<br />".
"This is my test email for learning how to send email using PHP mail function <br />".
"Thank You";
$headers = "From: $fromrnContent-type: text/html";
if(mail($to,$subject, $message, $headers))
{
echo "MAIL SENT SUCCESSFULLY";
}
else
{
echo "SOME ISSUE WITH MAIL SENDING in SERVER";
}
?>

In most of the cases we need to send email from a contact form in our website. Most of the business websites need this functionality , that their user can send and enquiry or messages by filling a contact form in their website.

Now look at a sample PHP program for sending email from a HTML contact form

Consider page contact.html contains the HTML contact form , and mail.php file contains the PHP scripts for sending email.
So contact.html will look like

<form method="post" action="mail.php" name="contact"><br />
Your name :<input type="text" name="username" /><br />
Email :<input type="text" name="useremail" /><br />
Message :<textarea cols="5" rows="5" name="message"></textarea><br />
<input type="submit" value="SEND EMAIL" name="submit" /><br />
</form>

When the user fills the data in form press SUBMIT button , the data is passed to the page mail.php where our mail(0 function is there . Now look at the code in mail.php

<?php
$username=$_POST['username'];
$from=$_POST['useremail'];
$to="to@gmail.com";
$subject="New Enquiry from ".$username;
$message=$_POST['message'];
$headers = "From: $fromrnContent-type: text/html";
if(mail($to,$subject, $message, $headers))
{
echo "MAIL SENT SUCCESSFULLY";
}
else
{
echo "SOME ISSUE WITH MAIL SENDING in SERVER";
}
?>

In this case, when a user submit the data an email will sent to “to@gmail.com” with a subject like “New Enquiry from JOHN” and content which is typed by the user in form.

This is only a basic introduction tutorial about mail function in PHP. In our later posts we will learn to send attachments and other advanced headers along with email.

PHP explode() – split a string by string into array

PHP explode() function is used for split a string by another string into an array. This function is used when we need to split a string using a specific character or string present in that string.
Its Syntax will be :
explode (delimiter string , string to explode , LIMIT );

Here delimiter string will declare at which string occurrence the split process should happen . And LIMIT is an optional parameter for specifying the maximum count of splitting. If we specify LIMIT parameter , maximum number of splitting will be the LIMIT value and the rest of string will be the last element in array.

We will get more clear picture about explode() function after seeing some examples.

Sample PHP program using explode() function

<?php
$data="How to split a string using explode";
$splittedstring=explode(" ",$data);
foreach ($splittedstring as $key => $value) {
echo "splittedstring[".$key."] = ".$value."<br>";
}
?>

Its output will be :

splittedstring[0] = How
splittedstring[1] = to
splittedstring[2] = split
splittedstring[3] = a
splittedstring[4] = string
splittedstring[5] = using
splittedstring[6] = explode

Here , we are trying to split the string at blank spaces with out optional parameter LIMIT value. And we can see that string is split at the positions where blank space occurred and stored in the array $splittedstring. We can retrieve the values splittedstring[0] for first split string and splittedstring[1] for the second part etc..
Here in this example I am looping through the array and output all the results.

Now look at a sample program with optional parameter LIMIT count with explode()

<?php
$data="How to split a string using explode";
$splittedstring=explode(" ",$data,3);
foreach ($splittedstring as $key => $value) {
echo "splittedstring[".$key."] = ".$value."<br>";
}
?>

Its output will be :

splittedstring[0] = How
splittedstring[1] = to
splittedstring[2] = split a string using explode

Here we can see that optional parameter is specified as 3 as limit count. So the string is split to three parts and last part contain the rest of the original string.

Now look at the next sample PHP program with explode() function

<?php
$data="http://www.youtube.com/watch?v=ZR0iBvof3MA";
$splittedstring=explode("?v",$data);
echo "Video ID is ".$splittedstring[1];
?>

Output will be :

Video ID is =ZR0iBvof3MA

Here we trying to split a youtube video url by a string ?v for getting its video id.

Optional parameter with negative value:
If we specified -LIMIT , then the last LIMIT number of splitted results wont return.
See the flowing example and its output for understand whats happening

<?php
$data="ONE TWO THREE FOUR FIVE";
$splittedstring=explode(" ",$data,-2);
foreach ($splittedstring as $key => $value) {
echo "splittedstring[".$key."] = ".$value."<br>";
}
?>

Its output will be :

splittedstring[0] = ONE
splittedstring[1] = TWO
splittedstring[2] = THREE

Here we can see that it wont store the last two components ( FOUR and FIVE ) in array.

Share
Share