Reputation: 12304
Basically I want to split an array element if it contains a comma, and preserve element order within the array.
So I have an element like this:
$array = ["coke", "joke", "two,parts", "smoke"];
And I want to turn it find the one with the comma, split it by the comma into two separate elements and maintain order as if nothing had happened.
This is the desired result:
$array = ["coke", "joke", "two", "parts", "smoke"];
Upvotes: 1
Views: 661
Reputation: 47864
This is the shortest, sweetest method. Simply join all of the elements into a comma-separated string, then split the string on every comma back into an array.
This will be the most efficient method as it will never make more than two function calls in total. The other answers use one or more function calls on each iteration of the input array which only slows the process down.
Also, using a case-insensitive strstr()
call on a comma makes no logical sense. The PHP manual even has a special Note saying not to use strstr()
for needle searching.
Code: (Demo)
$array = ["coke", "joke", "two,parts", "smoke"];
var_export(explode(',', implode(',', $array)));
Output:
array (
0 => 'coke',
1 => 'joke',
2 => 'two',
3 => 'parts',
4 => 'smoke',
)
Upvotes: 1
Reputation: 2375
Short and sweet: let's use array_reduce()
with the array being reduced to an array:
$arr = ["coke", "joke", "two,parts", "smoke"];
function filter($v1,$v2)
{
return array_merge($v1,explode(',',$v2));
}
print_r(array_reduce($arr,"filter",[]));
No explicit iterating nor temporary variables, needed!
Upvotes: 2
Reputation: 15141
Hope this will be helpful, here we are using foreach
and explode
to achieve desired output.
<?php
ini_set('display_errors', 1);
$array = ["coke", "joke", "two,parts", "smoke"];
$result=array();
foreach($array as $value)
{
if(stristr( $value,","))
{
$result= array_merge($result,explode(",",$value));
}
else
{
$result[]=$value;
}
}
print_r($result);
Upvotes: 3
Reputation: 17
Create new array which will have fixed values. Then iterate trough original array and explode each element and append it to new array.
Upvotes: -2