Home > OS >  Check if array can be converted to int then convert laravel
Check if array can be converted to int then convert laravel

Time:10-30

I have an array collection that I converted to array using toArray(). Which changes all items to a string. I want to check every item that can be converted to an integer/decimal. The array looks like this

['first_name'] => 'Jake',
['last_name'] => 'Doe',
['age'] => '13', (Change this to an integer/decimal)
['address'] => 'Ivory Street'
['allowance'] => '3000' (Change this to an integer/decimal)

I'm using Laravel/Livewire

CodePudding user response:

you should check first if the item can be converted to integer then convert it if can using ctype_digit, otherwise do nothing:

 $resultArray=  array_map(function ($item){
          if(ctype_digit($item))
            return floatval($item);
          else return $item;
        },$array);
return $resultArray;

CodePudding user response:

So many ways to convert int or float. This is the logic :

$data = collect([
    'first_name' => 'Jake',
    'last_name' => 'Doe',
    'age' => '13',
    'address' => 'Ivory Street',
    'allowance' => '3000',
    'float?' => '0.6'
])
->map(function($item){
    return (is_numeric($item))
        ? ($item == (int) $item) ? (int) $item : (float) $item
        : $item;
})
->toArray();

dd($data);

Result :

array:6 [
  "first_name" => "Jake"
  "last_name" => "Doe"
  "age" => 13
  "address" => "Ivory Street"
  "allowance" => 3000
  "float?" => 0.6
]
  • Related