PHP Explode and Implode
PHP explode() and implode() can be used to split string into array or join the array elements as string.Explode
Explode function breaks the string into array, it accepts three arguments, first one is the delimiter that specifies where to break the string, second one is the string that needs splitting, and third one is not mandatory but it tells how many array to return.PHP
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
<?php
$string_to_explode = 'this-string-needs-some-exploding';
//Break string into an array
$exploded_string = explode('-', $string_to_explode);
print_r($exploded_string);
//output :
// Array ( [0] => this [1] => string [2] => needs [3] => some [4] => exploding )
echo $exploded_string[0];
echo $exploded_string[1];
?>
Implode
Unlinke explode() function, implode() joins the array values into a string, and it accepts two arguments, first argument the separator which specifies what character to use between array elements, and second one is the collection of array values.PHP
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
<?php
//array values
$array_value = array('eat','sleep','walk','read','write','watch','move');
//join all array values with "-" hyphen
//output : eat-sleep-walk-read-write-watch-move
echo implode('-', $array_value);
?>