1

I want to remove an item from an array. I can write this:

$item = array(
    'id' => 1
    'name' => 'name'
);

$item2 = $item;
unset($item2['id']);
$names[] = $item2;

but the last 3 lines are somewhat "cumbersome", soo un elegant. Can it be solved without creating $item2 ? Something like:

$item = array(
    'id' => 1
    'name' => 'name'
);

$names[] = array_ignore_index('id', $item);
4
  • you can do unset($item['id']); Commented Apr 18, 2016 at 7:35
  • and after unset, you can use array_values($array) to reindex. Commented Apr 18, 2016 at 7:37
  • @deceze: thefreedictionary.com/red-handed Commented Apr 18, 2016 at 9:19
  • 1
    Yeah, "in the act of committing a crime or doing something wrong or shameful"...?! :) Commented Apr 18, 2016 at 10:26

4 Answers 4

3

From your codes, I can see that you are trying to get the names[] from item array. One possible simple solution for this specific scenario:

For example IF you have :

$items = array(
    array(
        //this is your item 1
        'id' => 1,
        'name' => 'name1'
    ),
    array(
        //this is item 2
        'id' => 2,
        'name' => 'name2'
    )
);

and you want to retrieve the names in the names array.

You can just do:

$names = array_column($items, 'name');

It will return:

Array
(
    [0] => "name1"
    [1] => "name2"
)

Please note this solution is best fit for this specific scenario, it may not fit your current scenario depending.

Sign up to request clarification or add additional context in comments.

Comments

1

The shortest out of the box solution is to create a diff of the array keys:

$names[] = array_diff_key($item, array_flip(['id']));

See http://php.net/array_diff_key.

Comments

1
function array_ignore_index($id,$item){ ///function 
     unset($item[$id]);
     return $item;
   }
$a=array('id'=>1,
     'name'=>'name');
$b=array_ignore_index('name',$a);
echo $b['name']; //create error id is not present

Here is the code for required operation..

Comments

0

You can use unset array column

Code is

unset($item['id']);

To test it

print_r($item);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.