I have a Laravel array and would like to modify the returned values.
$array = ['hr-34', 've-53', 'dv-65'];
I want to remove everything before the dash and the dash itself and return the following array.
$array = ['34', '53', '65'];
CodePudding user response:
You can do something like this:
foreach ($c as $key => $value) {
$pieces = explode('-', $value);
$array[$key] = $pieces[1];
}
You have used the tag collections
. So if it's a collection you can use this function:
$c->map(function ($item) {
return explode('-', $item)[1];
})
CodePudding user response:
Steps to follow:
- define blank array $new_array (to fill single value from foreach loop).
- get single value using foreach loop.
- use strstr for remove everything before dash and remove '-' using str_replace.
- fill single value in $new_array.
- return $new_array outside foreach loop.
Below is the code -
$array = ['hr-34', 've-53', 'dv-65'];
$new_array = array();
foreach($array as $key=>$result){
$data = str_replace('-', '', strstr($result, '-'));
$new_array[]= $data;
}
print_r($new_array);
That's all!
CodePudding user response:
https://www.php.net/manual/en/function.array-map.php https://www.php.net/manual/en/function.explode.php
$array = array_map(function ($item) {
return explode('-', $item)[1];
}, $array)
Edit:
As you changed title from array
to collection
you can use:
https://laravel.com/docs/9.x/collections#method-map
$collection->map(...)
in a similar way to array_map(...)
CodePudding user response:
$array = ['hr-34', 've-53', 'dv-65'];
$array = collect($array)
->map(fn($item) => explode('-', $item)[1])
->all();
/**
* array:3 [
* 0 => "34"
* 1 => "53"
* 2 => "65"
* ]
*/
dd($array);
Here this code in sandbox
CodePudding user response:
you can use regex with preg_replace
as :
$new = array_map(function ($item) {
return preg_replace('/^([^-]) -/', '', $item);
}, $array);
result :
array:3 [
0 => "34"
1 => "53"
2 => "65"
]