Pranav Unde
Pranav Unde

Reputation: 193

Remove prefixes from array strings and implode with commas

I have following array.

 Array(
    [deselected_attachment_ids] => Array
    (
        [0] => 16883477_12869438
        [1] => 16883478_12869439
    )
)

Required output from array = array( 12869438,12869439);

I used following code.

 $implodeArray = implode(',',$testArray);

It gives me warning

Array to string conversion

How should I get required output array?

Upvotes: 0

Views: 73

Answers (2)

mickmackusa
mickmackusa

Reputation: 47903

You can let preg_replace() traverse the array for you and remove the unwanted parts. While regex isn't known for being fast, it is a direct, one-function solution.

Code: (Demo)

$array=['deselected_attachment_ids'=>['16883477_12869438','16883478_12869439']];
$result=preg_replace('/^\d+_/','',$array['deselected_attachment_ids']);
var_export($result);

Output:

array (
  0 => '12869438',
  1 => '12869439',
)

Or you can use a foreach loop with explode(): (Demo)

$array=['deselected_attachment_ids'=>['16883477_12869438','16883478_12869439']];
foreach($array['deselected_attachment_ids'] as $v){
    $result[]=explode('_',$v)[1];
}
var_export($result);
// same result

And finally, if you don't want to use regex and you don't want to generate temporary arrays (from explode() call) on every iteration, you can use substr() and strpos().

$array=['deselected_attachment_ids'=>['16883477_12869438','16883478_12869439']];
foreach($array['deselected_attachment_ids'] as $id){
    $result[]=substr($id,strpos($id,'_')+1);
}
var_export($result);

Upvotes: 0

splash58
splash58

Reputation: 26153

Use explode to split string to two parts and get the 2nd

$res = array_map(function($x) { return explode('_', $x)[1]; },
                 $arr['deselected_attachment_ids']);
print_r($res);

demo

Upvotes: 1

Related Questions