Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

hash

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!

like image 976
Alex Avatar asked Mar 01 '10 05:03

Alex


2 Answers

{$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;
}
like image 191
codaddict Avatar answered Sep 28 '22 11:09

codaddict


<?php
  $histogram = array_count_values($array);
?>
like image 38
Matthew Avatar answered Sep 28 '22 13:09

Matthew