-5

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

kgcusi
  • 215
  • 7
  • 18

1 Answers1

1

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
]
Wahyu Kristianto
  • 8,719
  • 6
  • 43
  • 68