0

I am doing in below way, is that method is fine or is that also possible with help of some functions. please suggest.

I have one array named $items and output is like below:

array (size=2)
  0 => 
    array (size=1)
      'value' => string '7' (length=1)
  1 => 
    array (size=1)
      'value' => string '14' (length=2)

But I need out put like below :

array (size=2)
  0 => int 7
  1 => int 14

And I did like this and got my required results:

    $new_array = array();
    foreach($items as $key=>$value){
     $new_array[] = $value['value'];
    }

var_dump($new_array);

array (size=2)
  0 => string '7' (length=1)
  1 => string '14' (length=2)

please suggest is this is right approach ?

jas
  • 177
  • 1
  • 10

2 Answers2

2

Try this:

$newArray = array_map(function($value) { return (int)$value['value']; }, $items);

or as suggested in comments by @MarkBaker

$new_array = array_column($items, 'value');
jas
  • 177
  • 1
  • 10
aslawin
  • 1,981
  • 16
  • 22
  • Thanks! I was just looking like to convert with some function like you did and without foreach loop. – jas Apr 07 '16 at 10:19
0

php int() casts a value to int ,just use it

 $new_array = array();
    foreach($items as $key=>$value){
     $new_array[] = (int)$value['value'];
    }

var_dump($new_array);
Jack jdeoel
  • 4,554
  • 5
  • 26
  • 52