0

I am trying to remove a key/value pair from an array but it does not seem to work. Basically, I make an API call which returns JSON. As such I do

$tempArray = json_decode($projects, true);

If I output $tempArray I see something like this

array:2 [
  0 => array:9 [
    "id" => 4
    "name" => "Some Project Name"
    "value" => "234"
    "user_id" => "1"
    "client_id" => "97"
    "contact" => "Jane Berry"
  ]
  1 => array:9 [
    "id" => 3
    "name" => "Another Project Name"
    "value" => "6"
    "user_id" => "1"
    "client_id" => "97"
    "contact" => "John Doe"
  ]
]

I essentially need to remove the value element so I do this

unset($tempArray['value']);

If I output $tempArray after the unset, it displays exactly the same as before, with the value element and value there.

What do I need to do to completely remove this from my array?

Thanks

1
  • There is no key called 'value' on the first level of your array. You would need to do something like unset($tempArray[0]['value']); Otherwise loop through it. Commented Aug 18, 2016 at 13:20

2 Answers 2

1

unset will not look recursivly to sub-array to remove the key value. Only if you have at first level a key named value will be removed. In your array first level keys are: 0 and 1. So to remove value from all sub-arrays you have to go throw all items from the array and unset it. You can do this with a simple foreach.

foreach($tempArray as $key => $data) { 
   unset($data['value']);
   $tempArray[$key] = $data; //Overwrite old data with new with value unset.
}

Now you will not have value key in sub-array items.

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

Comments

1

As per my comment, you have no key called 'value' which is a top level key in your array. If you array looked like this:

$myArray = array(
    "value" => "My Value to delete",
    "anotherKey" => "hello world",
);

Then you could do unset($myArray['value']); and you would remove the key and value. In your case, the key you are looking for is nested under a numeric key [0] or [1]. You could reference these specifically like this:

unset($tempArray[0]['value']);

but what I imagine you are looking to achieve is to remove any trace of the key value from your array in which case you would be better off doing something like this:

foreach($tempArray as &$nestedArray){
    unset($nestedArray['value']);
}

Note the & symbol before the $nestedArray. This means 'pass by value' and will actually update the $tempArray in a single line without the need for anything else.


Further Reading:

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.