Search code examples
phparraysreplacesanitization

Remove everything before the dash from a Laravel array


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'];


Solution

  • 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!