All the cool kids these days are using Ruby...however I am stuck in a PHP world at the moment. I've been doing Ruby on some side projects and its got me thinking in a ruby mindset...and I wonder.. can PHP do that? And I've found a few things that might make a PHP geek's life a bit easier or at least PHP a little more tolerable.
Looping
Yes yes, the good old for loop.
for ($i = 1, $i <= 10; $i++) { print "Processing $<br>"; }
The simple act of doing something 10 times. Ugly huh? He's one way to do it in Ruby..
1.upto(10) do |i| puts "Processing #{i}" end
Nifty, huh? Meet PHP's range function
foreach(range(1, 10) as $i) { print "Processing $i"; }
The range function returns an array with values 1 through 10. I almost NEVER use for anymore, most of the time I use foreach. Range can also return letters, such as a through z, but I find that a bit obscure for what I do. I don't know if I've ever needed to loop through the alphabet in any of my web development
Do this to each element in my array
Another thing I was finding I really liked in ruby was the each method. In ruby, to loop through an array and pass each element to a function:
def sayHi ( member ) puts "Hi #{member}" end family = ['mom', 'dad, 'brother', 'sister'] family.each |member| { sayHi (member) }
A bit simplistic of an example, I know. Here's some php
function sayHi($member) { print "Hi $member"; } $family = array('mom','dad','brother','sister');
# normally I'd do it like this: foreach($family as $member) { sayHi($member); }
#but recently found this command array_walk($family, 'sayHi' )
You could argue that this is simplier than the Ruby code above. Yeah, maybe. It would help if it wasn’t such a badly named function (nothing new there for us php programmers). I think array_each would of been a better name...but phish..what do I know?
Ok, so arrays can walk but can they run? (sorry, bad joke), err can they run a function on each element and return something? Yes they can, check out array_map! Beware the parameters are switched in map, function name first then array. Doh. One of the most practical uses I've found for map is trimming data coming from a form:
$raw_data = $_POST['form']; $trimmed_data = array_map('trim',$raw_data);
#previously I would have done foreach($raw_data as $name => $value) { $trimmed_data[$name] = trim($value); }
Another good use for map is cleaning the data, stripping slashes..etc.
Read up on the php documentation for range and array_map, you might find some more interesting uses for them! Even if you don't use ruby, take a look at the ruby functions. You might learn something :)
PHP Links:
Ruby Links: