1

I want to empty all values by empty string in a PHP array, and keeping all the keys names recursively.

Example:

<?php
$input = 
['abc'=> 123,
    'def'=> ['456', '789', [
    'ijk' => '555']
    ]
];

I want my array to become like this:

<?php
$output = ['abc'=> '',
    'def'=> ['', '', [
        'ijk' => '']
      ]
];
1
  • 1
    arra_walk_recursive - eval.in/757067 Commented Mar 19, 2017 at 8:50

1 Answer 1

4

You should use recursive function:

function setEmpty($arr)
{
    $result = [];
    foreach($arr as $k=>$v){
    /*
        * if current element is an array,
        * then call function again with current element as parameter,
        * else set element with key $k as empty string ''
        */
        $result[$k] = is_array($v) ? setEmpty($v) : '';
    }
    return $result;
}

And just call this function with your array as the only parameter:

$input = [
    'abc' => 123,
    'def' => [
        '456',
        '789', [
            'ijk' => '555',
        ],
    ],
];

$output = setEmpty($input);
Sign up to request clarification or add additional context in comments.

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.