Home » Php » php – delete all values from an array while keeping keys intact

php – delete all values from an array while keeping keys intact

Posted by: admin April 23, 2020 Leave a comment

Questions:

Do I really have to do this to reset an array ??

foreach ($array as $i => $value) {
    unset($array[$i]);
}

EDIT:

this one makes more sense, as the previous one is equivalent to $array=array();

foreach ($array as $i => $value) {
    $array[$i]=NULL;
}
How to&Answers:

Define this function and call it whenever you need it:

function erase_val(&$myarr) {
    $myarr = array_map(create_function('$n', 'return null;'), $myarr);
}

// It's call by reference so you don't need to assign your array to a variable.
// Just call the function upon it
erase_val($array);

That’s all!

Answer:

$keys = array_keys($array);
$values = array_fill(0, count($keys), null);
$new_array = array_combine($keys, $values);

Get the Keys

Get an array of nulls with the same number of elements

Combine them, using keys and the keys, and the nulls as the values

As comments suggest, this is easy as of PHP 5.2 with array_fill_keys

$new_array = array_fill_keys(array_keys($array), null);

Answer:

Fill array with old keys and null values

$array = array_fill_keys(array_keys($array), null)

Answer:

There is no build-in function to reset an array to just it’s keys.

An alternative would be via a callback and array_map():

$array = array( 'a' => 'foo', 'b' => 'bar', 'c' => 'baz' );

With regular callback function

function nullify() {}
$array = array_map('nullify', $array);

Or with a lambda with PHP < 5.3

$array = array_map(create_function('', ''), $array);

Or with lambda as of PHP 5.3

$array = array_map(function() {}, $array);

In all cases var_dump($array); outputs:

array(3) {
  ["a"]=> NULL
  ["b"]=> NULL
  ["c"]=> NULL
}

Answer:

Flip the array to get the keys, then gives all keys the value NULL:

array_fill_keys(array_flip($array), NULL);

About array_fill_keys():

The array_fill_keys() function fills an array with values, specifying
keys.

About array_flip():

The array_flip() function flips/exchanges all keys with their
associated values in an array.

Answer:

foreach($a as &$v)
   $v = null;

The reasoning behind setting an array item to null is that an array needs to have a value for each key, otherwise a key makes no sense. That is why it is called a key – it is used to access a value. A null value seems like a reasonable choice here.

Wrap it in a [reusable] procedure:

function array_purge_values(&$a)
{
    foreach($a as &$v)
       $v = null;
}

Keep in mind though that PHP version starting from 5.3 pass values to functions by reference by default, i.e. the ampersand preceding argument variable in the function declaration is redundant. Not only that, but you will get a warning that the notion is deprecated.

Answer:

If you need to nullify the values of a associative array you can walk the whole array and make a callback to set values to null thus still having keys

array_walk($ar,function(&$item){$item = null;});

In case if you need to nullify the whole array just reassign it to empty one

$ar = array();

Answer:

unset would delete the key, You need to set the value to null or 0 as per your requirement.

Example

Answer:

I don’t get the question quite well, but your example

foreach ($array as $i => $value) {
    unset($array[$i]);
}

is equivilent to

$array = array();

Answer:

Why not making an array with required keys and asinging it to variable when you want reset it?

function resetMyArr(&$arr)
{
 $arr = array('key1'=>null,'key2'=>null); 
}

Answer:

This is a fairly old topic, but since I referenced to it before coming up with my own solution for a more specific result, so therefore I will share with you that solution.

The desired result was to nullify all values, while keeping keys, and for it to recursively search the array for sub-arrays as well.

RECURSIVELY SET MULTI-LEVEL ARRAY VALUES TO NULL:

function nullifyArray(&$arrayData) {

  if (is_array($arrayData)) {
    foreach ($arrayData as $aKey => &$aValue) {
      if (is_array($aValue)) {
        nullifyArray($aValue);
      } else {
        $aValue = null;
      }
    }
    return true;     // $arrayData IS an array, and has been processed.
  } else {
    return false;    // $arrayData is NOT an array, no action(s) were performed.
  }

}

And here is it in use, along with BEFORE and AFTER output of the array contents.

PHP code to create a multilevel-array, and call the nullifyArray() function:

// Create a multi-level array.
$testArray = array(
    'rootKey1'              =>  'rootValue1',
    'rootKey2'              =>  'rootValue2',
    'rootArray1'            =>  array(
        'subKey1'           =>  'subValue1',
        'subArray1'         =>  array(
            'subSubKey1'    =>  'subSubValue1',
            'subSubKey2'    =>  'subSubValue2'
        )
    )
);

// Nullify the values.
nullifyArray($testArray); 

BEFORE CALL TO nullifyArray():

Array
(
    [rootKey1] => rootValue1
    [rootKey2] => rootValue2
    [rootArray1] => Array
        (
            [subKey1] => subValue1
            [subArray1] => Array
                (
                    [subSubKey1] => subSubValue1
                    [subSubKey2] => subSubValue2
                )

        )

)

AFTER CALL TO nullifyArray():

Array
(
    [rootKey1] => 
    [rootKey2] => 
    [rootArray1] => Array
        (
            [subKey1] => 
            [subArray1] => Array
                (
                    [subSubKey1] => 
                    [subSubKey2] => 
                )

        )

)

I hope it helps someone/anyone, and Thank You to all who previously answered the question.

Answer:

Just do this:

$arrayWithKeysOnly = array_keys($array);

http://php.net/manual/en/function.array-keys.php

EDIT: Addressing comment:

Ok, then do this:

$arrayWithKeysProper = array_flip(array_keys($array));

http://www.php.net/manual/en/function.array-flip.php

EDIT: Actually thinking about it, that probably won’t work either.