Website Development Prices

Tuesday, March 15, 2016

Prosledjivanje nizova u funkciju (Passing arrays in function)

Pored podataka koji predstavljaju obicne promenljive, u funkcije mozete da prosledite i nizove. 

Primer: kreiracemo funkciju stampaj_niz, koja stampa sadrzaj niza.

<?php

$motor[0] = "suzuki";
$motor[1] = "honda";
$motor[2] = "kawasaki";
$motor[3] = "yamaha";

stampaj_niz($motor);

function stampaj_niz($niz)
{
for ($indeks = 0; $indeks < count($niz); $indeks++) {
echo "Motor $indeks: ", $niz[$indeks], "<br />";
}

}

?>

Rezultat:


Motor 0: suzuki
Motor 1: honda
Motor 2: kawasaki
Motor 3: yamaha


Primer 2: izracunacemo srednju cenu motora. Cene se nalaze u nizu.

<?php

$cena_motora[0] = 2500;
$cena_motora[1] = 1900;
$cena_motora[2] = 3700;
$cena_motora[3] = 2550;

srednja_cena($cena_motora);

function srednja_cena($cena)
{
$ukupno = 0;
for ($indeks = 0; $indeks < count($cena); $indeks++) {
$ukupno += $cena[$indeks];
}

echo "Prosecna cena = ", $ukupno / count($cena);

}

?>

Rezultat:

Prosecna cena = 2662.5

In addition to the data representing the ordinary variables, to the function you can pass arrays.

Example: we will create function print_array, which prints the contents of the array.

<?php

$motorcycle[0] = "suzuki";
$motorcycle[1] = "honda";
$motorcycle[2] = "kawasaki";
$motorcycle[3] = "yamaha";

print_array($motorcycle);

function print_array($array)
{
for ($index = 0; $index < count($array); $index++) {
echo "Motorcycle $index: ", $array[$index], "<br />";
}

}

?>

Result:

Motorcycle 0: suzuki
Motorcycle 1: honda
Motorcycle 2: kawasaki
Motorcycle 3: yamaha


Example 2: we will calculate the average price of the motorcycles. Prices are in array.

<?php

$motorcycle_price[0] = 2500;
$motorcycle_price[1] = 1900;
$motorcycle_price[2] = 3700;
$motorcycle_price[3] = 2550;

average_price($motorcycle_price);

function average_price($price)
{
$total = 0;
for ($index = 0; $index < count($price); $index++) {
$total += $price[$index];
}

echo "Average price = ", $total / count($price);

}

?>

Result:

Average price = 2662.5

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.