Fadly Dzil Fadly Dzil - 1 year ago 66
PHP Question

Change data type in specific element array in PHP

I have an array based query into MySQL.
If the array that come like this:

array (size=6)
0 =>
array (size=2)
'name' => string 'Login' (length=5)
'y' => string '1' (length=1)
1 =>
array (size=2)
'name' => string 'Printer' (length=7)
'y' => string '2' (length=1)
2 =>
array (size=2)
'name' => string 'Monitor' (length=7)
'y' => string '0' (length=1)
3 =>
array (size=2)
'name' => string 'Computer' (length=8)
'y' => string '0' (length=1)
4 =>
array (size=2)
'name' => string 'Network' (length=7)
'y' => string '0' (length=1)
5 =>
array (size=2)
'name' => string 'Lain Lain' (length=9)
'y' => string '0' (length=1)


How can I make all key 'y' as integer ?

Answer Source

you can use array_map to handle all elements in array

$arr = [
  ['x' => 'str', 'y' => '1'],
  ['x' => 'str', 'y' => '2'],
  ['x' => 'str', 'y' => '3']
];


print_r(array_map(function($el) {
  $el['y'] = intval($el['y']);
  return $el;
}, $arr));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download