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 reall开发者_JAVA技巧y don't know anything of Perl but I'm trying).
So how do I put this {$histogram{$value}++}
into PHP?
Thanks!
{$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;
}
<?php
$histogram = array_count_values($array);
?>
foreach my $value (@_) {$histogram{$value}++}
It is a single line variant of:
foreach my $value (@_) {
$histogram{$value}++
}
精彩评论