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

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  ?>

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
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.