PHP: Delete all Values to Reuse a Keyed Array CodeUnit 25 MAR 2010

It’s sometimes pretty valuable to reuse array structures if you’re kind of doing a task over and over again, and don’t necessarily want to recreate the array’s keyed structure from scratch with each iteration. In other words, it would be really nice to have a function that automatically sets every element in an array to null but doesn’t actually mess up the array in the process.

Sounds pretty logical and something that most people could use, but believe it or not, no native little PHP function actually exists to do this for us! O.O

Okay, so now that you are over that little bit of shock and horror, let’s quickly whip up some code to do the job ourselves. First, we’ll start be declaring a function that returns a blank or in this case empty string value:

function clearValue($value)
{
	$value = '';
	return $value;
}

Right, the next step is then to apply the handy array_map function we discussed previously in this blog, forcing it to apply our newly created function to the array at hand.

$qsvalues = array_map("clearValue",$qsvalues);

And Bob’s your uncle. The keyed array $qsvalues will now be sitting with a blank string in each and every one of its elements, exactly what we were looking for! :)

Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.

  • Nice article, im a big fan of the blog thanks.
    Regards,
    John McCathery
    .-= Walking Holidays in ´s last blog ..New Site! =-.

  • Nice article, im a big fan of the blog thanks.
    Regards,
    John McCathery
    .-= Walking Holidays in ´s last blog ..New Site! =-.

  • Dd

    array_reduce($r, create_function(“” , “return ”;”))