0

A variable called $result

When print_r ($result); It goes:

Array
(
    [0] => iPhone
)
Array
(
    [0] => iOS
)
Array
(
    [0] => Safari
)

Seems like there are 3 Arrays in this $result, but I want to marge it to one and give theme order, I've tried array_merge(), and array_combine(), but none of theme get the result I want, what I really want is:

Array( 'iPhone', 'iOS', 'Safari' )

So I could output one of them using $results[0] or $results[1]...

How can I achieve that? Thanks alot.

Duke
  • 81
  • 7
  • Use `array_merge()` function [array_merge()](https://www.php.net/manual/en/function.array-merge.php) –  Sep 26 '19 at 11:50
  • I've tried array_merge($result), but this function requires at lest 2 variable, it did't work at this point. – Duke Sep 26 '19 at 11:52
  • Check [this answer](https://stackoverflow.com/a/1320156/8398549) in the duplicate, it [works](http://sandbox.onlinephpfunctions.com/code/4c626a03fb0a8f2eb59deb219360b901649fb920) for your case. – Cid Sep 26 '19 at 11:59
  • try this one `$result = array_merge(...$result);` – Joseph Sep 26 '19 at 12:00

1 Answers1

3

Use array_merge with ... splat operator

 $result = array_merge(...$array);

OR

 $result = call_user_func_array('array_merge', array($a));

For example :- https://3v4l.org/38Q5h

Rakesh Jakhar
  • 6,380
  • 2
  • 11
  • 20
  • $names = explode(' ', $name); $result = array_merge(...$names); var_dump($result); Thanks Rakesh, I tried your way like above, but get the warning: : array_merge(): Expected parameter 1 to be an array, string given in ..on line.. But the $names is an Array for sure. How weird is that. – Duke Sep 26 '19 at 12:22
  • @Duke check the link mentioned after the answer. – Rakesh Jakhar Sep 26 '19 at 12:25
  • Thank you, still get the warnings and I will double check my code and your example, thanks very much! – Duke Sep 26 '19 at 12:31
  • 1
    @Duke i have mentioned the other solution if you have older version of php – Rakesh Jakhar Sep 26 '19 at 12:34
  • I've tried your second solution, but it returns : array(1) { [0]=> string(6) "iPhone" } array(1) { [0]=> string(3) "iOS" } array(1) { [0]=> string(6) "Safari" } LOL, I think my $array must have some bugs in it, maybe it is not a string before I explode it? I will dig about that. My php version is 7.3, should not be the version problem. Thanks again! – Duke Sep 26 '19 at 12:43
  • I’m a fool... the reason why it always got 3 arrays is I was coding inside a “foreach”, when I go outside, everything works perfect, both of your ways works well, thank you for helping me! – Duke Sep 27 '19 at 04:31