The big bottleneck in the is that it's recursive: if you're computing hadamard(5), you end up with PHP having to keep track of five entire functions-in-progress, with all their local variables and so forth. That can get expensive; luckily it's almost right at the start, so there's little "in progress" at that point, but PHP still has to do all the work involved with calling a user-defined function. The first approach also uses array_merge() a couple of times, which means more function-call overhead.
I also half-suspect that foreach looping over array indices is a wee bit slower than ordinary for loops. In the second all there's nothing fancier than some increments and a few bit-operations.
'Course, all this is probably academic until the matrices get really big. In which case a bit of memory conservation might be in order:
hadamard($n=0)
{
$one=1;
$mone=-1;
for($x=0;$x<(1<<$n);$x++)
for($y=0;$y<(1<<$n);$y++)
{
$h[$x][$y]=0;
for($i=0;$i<$n;$i++) if($x&$y&(1<<$i)) $h[$x][$y]++;
$h[$x][$y]=($h[$x][$y]&1?$mone:$one);
}
return $h;
}
The difference between this one and the previous is that the previous requires 2(2n) locations in memory to store lots of 1's and -1's, while this one only stores a single 1 and a single -1 and just points to those as necessary.
Plus, I just felt like doing it again, only smarter 🙂