Explode and Implode Functions |
| Written by phpecho.com | |||
The explode function is used to split a given string into multiple parts based on given seperators. For example, if we want to split a comma separated input into various parts, then explode is the ideal option. For example, assume that we have a string: United Kingdom,Brazil,France,China,Japan We want to get each country name as a separate variable. In this case, the explode function solves our problem admirably. Our code snippet shows how we resolve the issue:
<?php
$string = "United Kingdom,Brazil,France,China,Japan";
$countries = explode(',',$string);
echo ("The countries are -");
echo ($countries[0]."-".$countries[1]."-".$countries[2]."-".$countries[3]."-".$countries[4]);
?>
The output of the above code is: The countries are -United Kingdom-Brazil-France-China-Japan Consider another example where we want to separate the domain name and the tld extension. So, if the user keys in google.com, we want to separate google and com and get that into separate variables. The program to do that would be:
<?php
//$input = $_POST['domainname'];
$input = "google.com";
$variables = explode('.',$input);
$name = $variables[0];
$ext = $variables[1];
echo ("The name is -".$name."<br>");
echo ("The extension is -".$ext);
?>
We would ideally get the complete domain name as an input from the user - that is we used the $_POST to get that input. To keep our example simple, we have assumed that the input is google.com. The exact inverse of the explode function is the implode function. In this case, the function will concatenate a set of strings using a common separator. For example, take the previous example. If we had the name and the extension and wanted to get the original domain name, we would assign the name and extension to an array and pass the separator (in our case, '.'), to the implode function. The code snippet below illustrates this:
<?php
$input = array('google','com');
$domainname = implode (".",$input);
echo ("The domain name is -".$domainname);
?>
The output for this program would be: The domain name is -google.com The implode function can be used in conjunction with the explode function. The explode function returns an array which can be passed as an argument to the implode function. Consider the following code snippet which is an extension of the first program we have written. <?php
echo ("Going to invoke explode function<br>");
$string = "United Kingdom,Brazil,France,China,Japan";
$countries = explode(',',$string);
echo ("The countries are -<br>");
echo ($countries[0]."-".$countries[1]."-".$countries[2]."-".$countries[3]."-".$countries[4]."<br>");
echo ("Going to invoke implode function<br>");
$implodeString = implode(",",$countries);
echo ("The imploded string is - ".$implodeString);
?>
In this case, what we have done is to pass the exploded array to the implode function. The implode function joins everything together using the separator.
|