1

How can I flat a multidimensional array after an explode with PHP ?

Example:

$string = "the colour of the sky is blue";
$pieces = explode(' ', $string);

Desired output:

array('the', 'colour', 'of', 'the', 'sky', 'is', 'blue');

Thanks.

Testy
  • 301
  • 2
  • 9
  • The output of your `explode()` call is already a flat single-dimension array. What exactly is your question? – Koala Yeung Apr 03 '19 at 02:57
  • @KoalaYeung, according to this link https://www.php.net/manual/fr/function.explode.php, the explode create a bi dimensional array. I would like array like this : `array('the', 'colour', 'of', 'the', 'sky', 'is', 'blue');`. – Testy Apr 03 '19 at 03:01
  • I'm not sure how you got the idea that it is a bi-dimensional array. The documentation stated that the function "Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter." That means it returns a single dimensional string array. You can use `var_dump` or `var_export` to review it. It gives exactly the output that you desired. – Koala Yeung Apr 03 '19 at 03:15
  • Please try to read [this code](http://sandbox.onlinephpfunctions.com/code/fc3bd8d79d94e83ba0c7f8d8b6f2a999812ccafe) and execute it. – Koala Yeung Apr 03 '19 at 03:20
  • @KoalaYeung, but how I can remove the key identifier if I don't need them? – Testy Apr 03 '19 at 10:53
  • PHP's array is both slices and hash. The only difference between single dimensional array (slice) and associative array (hash) is they have numerical keys (0, 1, 2 ...) instead of string keys. Having numerical key is a normal behavior of slices (e.g. `$pieces[0]`). Why do you "need" to "remove" them at all? Leave them be and it is OK. – Koala Yeung Apr 04 '19 at 03:19
  • Or put it simply, you cannot remove the keys from an array. Array is key value pairs in PHP. The notion `array('the', 'colour', 'of', 'the', 'sky', 'is', 'blue');` creates an array `array(0 => 'the', 1=> 'colour', 2 => 'of', 3 => 'the', 4 => 'sky', 5 => 'is', 6 => 'blue');`. They are identical in PHP. Keys are automatically assigned and cannot be removed. – Koala Yeung Apr 04 '19 at 03:28

0 Answers0