delete all values from an array while keeping keys intact

$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);

Fill array with old keys and null values

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


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
}

Tags:

Php

Arrays