Guidelines

This site is for tech Q&A. Please keep your posts focused on the subject at hand.

Ask one question at a time. Don't conflate multiple problems into a single question.

Make sure to include all relevant information in your posts. Try to avoid linking to external sites.

Links to documentation are fine, but in addition you should also quote the relevant parts in your posts.

1 vote
418 views
418 views

I have an array with a structure like this. Now I would like to unset the "answer" element. How should I do this using unset() or similar PHP functions?

[style] => light
[buttons] => Array (
    [flag] => Array (
        [tags] => name="q_doflag" onclick="qa_show_waiting_after(this, false);"
        [label] => Flag this
        [popup] => Flag this thing 
        )
    [answer] => Array (
        [tags] => name="q_doanswer" id="q_doanswer" onclick="return qa_toggle_element('anew')"
        [label] => answer this
        [popup] => Answer this button
        )
    )
in Scripting
retagged by
by (50)
1 5
edit history

Please log in or register to answer this question.

2 Answers

1 vote

I think I solved my problem.
Here's what I did:

unset($array['buttons']['answer']);
by (50)
1 5
edit history
 
That looks about right if you want to remove the entire key.
 
FTR, it's perfectly fine to accept your own answer, since it's a solution you found yourself.
1 vote

Depends on what result exactly you want to achieve. Do you want to remove just the value of the "answer" key, replace the value with a different value, or remove the key entirely?

I'll be using the following simplified data structure for demonstration purposes:

php > $a = Array("a" => Array("b" => 2, "c" => Array("d" => 4, "e" => 5)));
php > print_r($a);
Array
(
    [a] => Array
        (
            [b] => 2
            [c] => Array
                (
                    [d] => 4
                    [e] => 5
                )
        )
)

To remove just the value of the (sub)key "c" you'd assign NULL to the key:

php > $a['a']['c'] = NULL;
php > print_r($a);
Array
(
    [a] => Array
        (
            [b] => 2
            [c] => 
        )
)

Similarly you'd assign the new value if you wanted to replace the current value:

php > $a['a']['c'] = Array("x" => "foo", "y" => "bar");
php > print_r($a);
Array
(
    [a] => Array
        (
            [b] => 2
            [c] => Array
                (
                    [x] => foo
                    [y] => bar
                )
        )
)

If you want to remove the key entirely you'd use the unset() function, as you've already discovered:

php > unset($a['a']['c']);
php > print_r($a);
Array
(
    [a] => Array
        (
            [b] => 2
        )
)
by (125)
3 19 33
edit history
...