Alex
Alex

Reputation: 5695

What does {$histogram{$value}++} mean in Perl?

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!

Upvotes: 5

Views: 874

Answers (3)

codaddict
codaddict

Reputation: 455350

{$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;
}

Upvotes: 11

Matthew
Matthew

Reputation: 48304

<?php
  $histogram = array_count_values($array);
?>

Upvotes: 5

Alan Haggai Alavi
Alan Haggai Alavi

Reputation: 74262

foreach my $value (@_) {$histogram{$value}++}

It is a single line variant of:

foreach my $value (@_) {
    $histogram{$value}++
}

Upvotes: 0

Related Questions