Monday, September 20, 2010

Php -Explode and Implode||Php arrays ,string and variables

The PHP function explode lets you take a string and blow it up into smaller pieces. For example, if you had a sentence, which contains name of 5 persons, you could ask explode to use the sentence’s commas “,” as dynamite and it would blow up the sentence into separate words, which would be stored in an array. The sentence “Ram, Ravish, Rajeev, Rakesh, Ramesh” would look like this after explode got done with it: Explode is a PHP function which let as divide a string into smaller pieces,explode is used to break up a string into chunks, it acts on a string, and returns an array. Ram
Ravish
Rajeev
Rakesh
Ramesh The explode() function breaks a string into an array. Syntax array explode(separator,string,limit)
Parameter Description Required/Optional
separator Specifies where to break the string Required.
string The string to split. Required.
limit Indicates t he maximum number of array elements to return Optional
For example to break a string $str, separated by , the syntax would be: explode (“,”,$str); Example:




$str="Ram,Ravish,Rajeev,Rakesh,Ramesh";
$arr=explode(",",$str);
?>


";
echo "Exploded Array\n
";
print_r($arr);

?>

When executed the above script will display following output: img You can also use foreach loop to print the content of array. Implode The implode works exactly opposite of explode function. The PHP function implode operates on an array and is known as the “undo” function of explode. If you have used explode to break up a string into chunks or just have an array of stuff you can use implode to put them all into one string. The implode function accepts to arguments: separator and the array Syntax: implode(separator,array)
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:



$arr=array("Ram","Ravish","Rajeev","Rakesh","Ramesh");
$str=implode(",",$arr);
?>

echo $str;
?>


On execution above script produces the following output: img Assignment 1. Convert the following String to Array ”Hello, World!; Welcome, to eBIZ Education; Thanks for visiting” first convert the string to Array by using “;” as separator, then using “,” as separator and finally using space “ ”

2. Convert the following Array to String: $my_arr1=array(“Mika”, “Mona”, “Mitali”, “Madhu”, “Megha”, “Meghna”);

No comments:

Post a Comment