Anyone help me How to Make a function that works same as explode and implode function
Lets first see in simple terms what does explode do: (from php.net)
Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter.
which means
explode(' ', '1 2 3 4 5 6 7 8'); // will return the array of strings
// array(
// 0 => '1',
// 1 => '2',
// 2 => '3',
// 3 => '4',
// 4 => '5',
// 5 => '6',
// 6 => '7',
// 7 => '8'
// )
In above example the delimiter is whitespace and the string is 1...8
Similarly lets break this out in pseudo code:
- Function takes 2 parameters, delimiter and string
- create an empty array
- Find the length of the string
- Find the first position of the delimiter in the string
- take the sub-string from the string till the first position of delimiter
- store the sub-string in an array
- Repeat the step 3-6 until the string length is zero.
- Return the array
function letsExplode(String $delimiter, String $string): array
{
$arr = [];
while(strlen($string) > 0)
{
$pos = strpos($string, $delimiter);
if($pos)
{
$arr[] = trim(substr($string, 0, $pos));
$string = ltrim(substr($string, $pos), $delimiter);
} else {
$arr[] = trim($string);
$string = '';
}
}
return $arr;
}
letsExplode(' ', '1 2 3 4 5 6 7 8'); or letsExplode(',', '1, 2, 3, 4, 5, 6, 7, 8');
// array(
// 0 => '1',
// 1 => '2',
// 2 => '3',
// 3 => '4',
// 4 => '5',
// 5 => '6',
// 6 => '7',
// 7 => ' 8'
// )