-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

2

1 Answer 1

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
]
Sign up to request clarification or add additional context in comments.

3 Comments

This is correct but now I'm facing a problem when I map an array when it has a value of null, it changes it to 0.00
No issue for null value. Are you sure?
My bad it works, but I had a problem in displaying it in my blade file. Which I also resolved, this is the answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.