About us Privacy Disclaimer Contact us
FAQ Help Advertising Feedback
Home Sitemap Search Donate us

  Home > Computer & I'net > Exploding and Imploding...

   Browse by title articles:
   What is hot:

Accessing Arrays

Sorting Arrays

Push and Pop

Exploding and Imploding

Regular Expressions

Metacharacters

Clickbank Security Using PHP
CD-ROM Problems
How to Get Accepted By Yahoo! - Without Headache
Variables
Prev articles12345678 9 101112Next articles



Exploding and Imploding


Computer & I'net articlesExploding and Imploding

by David Stanley    



Exploding and imploding refers to changing between a string and an array. You can take a specific string and create an array out of the words or vice versa.

Using the explode command will create an array from a string.

Here is a sample string to start things off :
 
<?php
$pantry = "tomatoes,oranges,bananas,potatoes,bread,apples";
?>

Now you have to figure out a common seperator element. In this case it is a comma seperating each word. In a normal sentence, it could be specifed as a space.

Time to explode this string into an array...

<?php
$pantry = "tomatoes,oranges,bananas,potatoes,bread,apples";
$pantry_food = explode(",",$pantry);
?>


The array called $pantry_food now contains 6 elements. The array keys range from 0 to 5 and contains the values of tomatoes to apples. Doing a quick array print out :
 
<?php
$count_total = count($pantry_food);
for ($counter=0; $counter<$count_total; $counter++){
$line = each ($pantry_food);
echo "$line[key] $line[value] <br />";
?>

results as :
0 tomatoes
1 oranges
2 bananas
3 potatoes
4 bread
5 apples

So exploding breaks the data apart, imploding brings the data together. The implode command will take the data from an array and assemble it into a single string.

We will use the newly created array from above and implode it into a new string.

<?php
$new_pantry = implode(" ",$pantry_food);
?>

Imploding uses a separator element as well. In this case, it adds the separator between each of the array elements when it creates the new string. The above example is using a space this time.

The new string :

<?php
echo "$new_pantry";
?>


Has the value of :
tomatoes oranges bananas potatoes bread apples



-----------------
Article by David Stanley. Visit his site http://www.htmlite.com. Reprinted with permission.





Investment




  Disclaimer | Privacy | Terms of useCopyright © 2004 Nice2know.com