Help me with this task, please.

Joined
Mar 22, 2023
Messages
3
Reaction score
0
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?
 
Joined
Mar 22, 2023
Messages
3
Reaction score
0
this is how it look in program.
 

Attachments

  • download.png
    download.png
    40.8 KB · Views: 11
Joined
Jul 4, 2023
Messages
366
Reaction score
41
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.";
?>

Bez tytułu.png


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.";
?>

Bez tytułu2.png
 
Last edited:

Ask a Question

Want to reply to this thread or ask your own question?

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.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top