Jump to content

Array Functions: Whats the difference between implode and explode?


eldan88

Recommended Posts

Well explode breaks a string into many array elements, and implode builds a string from array elements.

 

Like so..

<?php
$str = "1,2,3,4,5";

echo $str; // would display "1,2,3,4,5"

$explodedstring = explode(",",$str);

echo $explodedstring[0]; // would display the first array element in this case "1"
echo $explodedstring[4]; // would display the fifth array element in this case "5"

$implodedstring = implode("-",$explodedstring);

echo $implodedstring; // would display "1-2-3-4-5"
?>

 

More here:

http://php.net/manual/en/function.explode.php

http://php.net/manual/en/function.implode.php

Link to comment
Share on other sites

Oh, I understand now! But isn't the explode function similar to just  calling a position within the array such as the following example...

<?php $array1 = array(4,8,15,16,23,42); ?>
<?php echo $array1[1] // Returns 8  ?>

Link to comment
Share on other sites

Nope. The explode function breaks up a string. In your example, $array1 is an array.

 

If you had a string "4,8,15,16,23,42", you could call the explode function on it to break it down into the equivalent of $array1. i.e.

 

<?php 
$array1 = array(4,8,15,16,23,42); 

$string = "4,8,15,16,23,42";
$array2 = explode($string);

//$array1 is the same as $array2

echo $array1[1]; // 8
echo $array2[1]; // 8
echo $string[1];  // will not work as expected
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.