1

Suppose I have such an array in php:

$ray =

Array
(
    [0] => Array
        (
            [id] => 1
            [0] => 1
            [ip] => 127.0.0.1
            [1] => 127.0.0.1
            [username] => local_me
            [2] => local_me
            [last_visit] => 2013-05-17 02:12:07
            [3] => 2013-05-17 02:12:07
        )

    [1] => Array
        (
            [id] => 2
            [0] => 2
            [ip] => 127.2.2.3
            [1] => 127.2.2.3
            [username] => Anonymous42
            [2] => Anonymous42
            [last_visit] => 2013-05-16 16:07:46
            [3] => 2013-05-16 16:07:46
        )

)

And I want to remove the ip (and '1' also) "column" for all elements of this array. How can I do this?

thanks !

2 Answers 2

4
foreach ($ray as &$item)
    unset($item['ip'],$item[1]);
Sign up to request clarification or add additional context in comments.

2 Comments

@Mark Parnell, why did you use '&' at '&$item'?
To pass the item by reference so it updates the original array.
1

This question was asked before here: PHP Remove elements from associative array

It's really simple to remove a key from an array, just use unset method.

foreach($ray as $key => $value){
   if(array_key_exists('id', $value){
      unset($ray[$key]['id'];
   }
   elseif(array_key_exists('1', $value){
      unset($ray[$key]['1'];
   }
}

Of course, there are few more options to do that more efficiently, I just try give an example.

1 Comment

Thanks ! But the definition of simple, for me, is "less lines of code", and I was trying to find (if exists) a function directly does that. Thanks for your effort, though !

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.