Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delete all values from an array while keeping keys intact

Tags:

arrays

php

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; } 
like image 985
jfoucher Avatar asked Feb 07 '10 15:02

jfoucher


2 Answers

$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); 
like image 124
Tyler Carter Avatar answered Oct 03 '22 00:10

Tyler Carter


Fill array with old keys and null values

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

like image 36
cubaguest Avatar answered Oct 02 '22 23:10

cubaguest