yohleb12

So i have array with numbers, and my task is to call function that inserts this value - this number appears x times.
I know how to do it with using foreach function twice, but i dont understand it this way.

<?php
\$sifra=array(100,200,100,90,30,200,44,100,90);
function Funkcija(\$sifra){
\$nove_sifre=array();
foreach(\$sifra as \$k => \$v){
if(isset(\$nove_sifre[\$v])){
\$nove_sifre[\$v]++;
}
else{
\$nove_sifre[\$v]=1;
}
}
return \$nove_sifre;
}
\$razlicitesifre= Funkcija(\$sifra);
foreach (\$razlicitesifre as \$k => \$v){
echo "<br>Šifra ".\$k." se ponavlja ".\$v." puta.";
}
?>

so unside function Funkcija there is \$nove_sifre =array();
and it loops thru \$sifra which is array and searches \$k =>\$v, i get that part
but then if(isset(\$nove_sifre[\$v])){
\$nove_sifre[\$v]++;
}
else{
\$nove_sifre[\$v]=1;
}
}
return \$nove_sifre;
}

i dont get that part, so if value is in \$nove_sifre, which is empty array, increase value by 1, else display it as 1
but \$nove_sifre is empty array so there is no value in first point, and second, if value is increased by 1, it wont count how many times that number is displayed, it would increase 100 to 101, an so on?

But the result is valid so thats what i dont get in this case.
How is everything above giving validd result if \$nove_sifre is empty andd \$v which arre numbers, increases by 1? and not the counter that counts how much times numbeer appears?

yohleb12

this is how it look in program.

Attachments

40.8 KB · Views: 11

yohleb12

and this is result.

Attachments

• aaa.png
77.1 KB · Views: 7

VBService

There is a short way to do this ... using array_count_values

e.g. [ on-line ]

PHP:
``````<?php
\$sifra = [ 100, 200, 100, 90, 30, 200, 44, 100, 90 ];
foreach (array_count_values(\$sifra) as \$key => \$val)
echo "<br>Šifra \$key se ponavlja \$val puta.";
?>``````

or

[ on-line ]

PHP:
``````<?php
\$sifra = [ 100, 200, 100, 90, 30, 200, 44, 100, 90 ];
foreach (array_count_values(\$sifra) as \$key => \$val)
echo '<br>Šifra ' . str_pad(\$key, 3, '&nbsp;', STR_PAD_LEFT) . " se ponavlja \$val puta.";
?>``````

Last edited:

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.