tags:

views:

156

answers:

3

The whole subroutine for the code in the title is:

sub histogram { # Counts of elements in an array
  my %histogram = () ;
  foreach my $value (@_) {$histogram{$value}++}
  return (%histogram) ;
}

I'm trying to translate a Perl script to PHP and I'm having difficulties with it (I really don't know anything of Perl but I'm trying).

So how do I put this {$histogram{$value}++} into PHP?

Thanks!

+10  A: 

{$histogram{$value}++} defines a block and in Perl the last line of a block doesn't need a terminating semicolon, so it is equivalent to {$histogram{$value}++;}.

Now the equivalent of hash in PHP is an associative array and we use [] to access the elements in that array:

$hash{$key} = $value;      // Perl
$ass_array[$key] = $value; // PHP

The equivalent function in PHP would be something like:

function histogram($array) {
    $histogram = array();
    foreach($array as $value) {
        $histogram[$value]++;   
    }
    return $histogram;
}
codaddict
PHP has a native function to do this: http://www.php.net/array_count_values
konforce
@Konforce: Good point. But I was just letting the OP know how his function can be translated to PHP using similar constructs.
codaddict
Thanks a lot, guys!
Alex
A: 
foreach my $value (@_) {$histogram{$value}++}

It is a single line variant of:

foreach my $value (@_) {
    $histogram{$value}++
}
Alan Haggai Alavi
+5  A: 
<?php
  $histogram = array_count_values($array);
?>
konforce
Thanks a lot, konforce!
Alex