No offense, that title sounds harsher than I really mean it in a way. PHP's stated goal is to help solve the "web problem". Unfortunately, as a language it kind of sucks. I've been having major problems writing some code I'm trying to write, so I decided to write my code in a largely functional style. PHP can't do that!!
Well, to be fair, maybe it can, but I have to force it to
I'll let you know how I make out.
Ok, some examples. I want to write a function to test if a "key" matches a certain "tag". A key matches a tag if, given a tag of "tag", the key is either "tag" or "tag<space>[anything else]". So, I'd want to write something like this functionally:
<?php
function isKeyEqual($key,$tag){
return substr($key, 0, strpos($fullkey, ' ')) == $tag;
}
?>
Unfortunately, substr won't work right if the space is not found, since strpos will return false if the space isn't found, which will be interpreted by substr as '0', which will make it always return the empty string.
substr isn't amenable to a functional style. If it took 0 to mean "the end of the string", or even NULL, I could do something like:
<?php
return substr($key, 0,
(($pos = strpos($fullkey, ' ')) !== false ? $pos : NULL)
) == $tag;
?>
But that doesn't work either. So I have to go fully back to the imperative style as so:
<?php
function isKeyEqual($key,$tag){
$pos = strpos($full_key, " ");
if($pos !== false){
return substr($full_key, 0, $pos) == $tagname;
}else{
return $full_key == $tagname;
}
}
Boo.
Update: I finally got my algorithm right. I think I'm finally done!
Well, you could do it with a regexp pattern in the likes of:
/^tag.$/ which matches anything that starts with "tag".