suppose I have this:
arrayValue[1] = "testing"; arrayValue[2] = ""; arrayValue[3] = ""; arrayValue[4] = "the"; arrayValue[5] = ""; arrayValue[6] = ""; arrayValue[7] = "waters";
I want to get this:
newArrayValue[1] = "testing"; newArrayValue[2] = "the"; newArrayValue[3] = "waters";
First of all, I'm able to do this with a little work but from a professional standpoint what would be the easiest way using compacting formulas? Could I flip the array or is there something faster?
Sam Fullman Compass Point Media
you could always do: ($loop=0;loop>count($arrayValue);$loop++) { if (!(arrayValue[$loop]) { $newArrayValue[] = $arrayValue[$loop]; } }
but it's not elegant.
woops if (!(arrayValue[$loop]=="") {
You're not really compacting the array, just removing elements that contain an empty string. I think a simple FOR loop would be quite effective, but you may have a peek at array_diff() aswell. But remember, elegant!=efficient
I try to use PHP's internal array functions when I can - so long as I don't have to go through too many contortions to use them - rather than build the loop by hand. Needless to say, native machine code is generally faster than compiled PHP!
$newArrayValue=array_filter($arrayValue, create_function('$var', ''return $var!=""'));
"native machine code is generally faster than compiled PHP!"
Actually, that's only true in some cases.
In this case for example, using your very clever and compact method is four times slower than using a for/if loop when the array is less than ten items. It takes twice as long with arrays up to 600 items, and above that you method still takes 20% longer than the FOR loop.
Strange but true.
<sulk>Huh, what's the point of having it then?</sulk>. Wanna guess it's that callback lambda function slowing it down?
Still, elegance was what was asked for... :-)
"Huh, what's the point of having it then?"
Convenience, pure and simple.
Just like it's a lot easier to write PHP than assembly, even though assembly is as fast as it gets.
Your solution sure was elegant, just not the fastest that's all.