Gardezi
Gardezi

Reputation: 2842

push certain elements into array php

I want to know that is there a way to insert certain elements of an array into a new array. I mean I have an array containing 10 objects. Each object has 3 or four fields for example id, name , age , username. now I want to insert the id's of all the objects into the new array with a single call.Is there anyway to do that.

$array = [ 
  [0] => [
      id   =>      
      name =>
  ],
  [1] = > [
      id   =>
      name =>
  ]
]

and so on now I want to insert all the id's of all the object into a new array with a single call. Is there a way to do that?

Upvotes: 0

Views: 271

Answers (4)

Geoffrey
Geoffrey

Reputation: 5432

You can use array_column.

$arr = [ ['id' => 1, 'username' => 'a'], ['id' => 2, 'username' => 'b'] ];
$ids = array_column($arr, 'id')
$ids == [1, 2]

Upvotes: 0

user2762134
user2762134

Reputation:

You could use array_walk which could be considered a "single call"

$array = array(0 => array('id', 'name', 'age'), 1 => array('id', 'name', 'age'));
array_walk($array, function($item, $key) {
    // $key is 0 or 1
    // $item is either id, name, age
});

Upvotes: 0

Ravi Hirani
Ravi Hirani

Reputation: 6539

Use array_map() function.

Here is your solution:-

 $ids = array_map( function( $arr ){
                    return $arr["id"];
                }, $arr );

 echo '<pre>'; print_r($ids);

Upvotes: 1

Tewdyn
Tewdyn

Reputation: 717

A basic foreach loop will do the job just fine

$firstArray = array(
  array(
    'id' => 1,
    'name' => 'abc'
  ),
  array(
    'id' => 2,
    'name' => 'def'
  ),
  array(
    'id' => 3,
    'name' => 'gh'
  )
);

$onlyIds = array();
$onlyKeys = array();

//To get the array value 'id'
foreach($firstArray as $value){
  $onlyIds[] = $value['id'];
}

//To get the array keys
foreach($firstArray as $key => $value){
  $onlyKeys[] = $key;
}

Upvotes: 0

Related Questions