katie hudson
katie hudson

Reputation: 2893

Unsetting element in array

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

Upvotes: 0

Views: 35

Answers (2)

Henders
Henders

Reputation: 1215

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:

Upvotes: 1

Daniel Dudas
Daniel Dudas

Reputation: 3002

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.

Upvotes: 1

Related Questions