Convert array values to int in Laravel

I have array named data in that i have sub array as place_id,when I print place_id from data array as

dd($data['place_id'])

It gives me result as

 array:1 [
   0 => "7"
   1 => "3"
 ]

I want values to be of type int as follows:

array:1 [
       0 => 7
       1 => 3
     ]

How will I get this result ?

Upvotes: 0

Views: 158

Answers (2)

MorganFreeFarm
MorganFreeFarm

Reputation: 3733

There is plenty of options:

1.Using foreach:

    foreach ($data as $k => $v) {
        $data[$k] = intval($v);
    }

    dd($data);

Result:

array:2 [
  0 => 7
  1 => 3
]

2.Using array_map() which is also for loop at the end:

 $data['place_id'] = array_map('intval', $data['place_id']);
 dd($data);

Result:

array:2 [
  0 => 7
  1 => 3
]

Upvotes: 1

Kien Nguyen
Kien Nguyen

Reputation: 2691

You can use intval() with array_map():

$data['place_id'] = array_map('intval', $data['place_id']);

Upvotes: 1

Related Questions