How to make a function that works in the same way as the explosion and implosion function

advertisements

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:

  1. Function takes 2 parameters, delimiter and string
  2. create an empty array
  3. Find the length of the string
  4. Find the first position of the delimiter in the string
  5. take the sub-string from the string till the first position of delimiter
  6. store the sub-string in an array
  7. Repeat the step 3-6 until the string length is zero.
  8. 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'
// )