Website Development Prices

Search Blog

Wednesday, April 20, 2016

Vracanje niza iz funkcije (Returning arrays from functions)

Ako vam je potrebno da funkcija vrati ceo niz, koristite iskaz return.

Primer: ako vam je potrebna funkcija koja duplira vrednosti u nizu, koja je se zove dupliranje_niza. Prvo cemo proslediti parametar (niza) toj funkciji. Zatim cemo u telu funkcije pomocu petlje proci kroz sve elemente, duplirati ih i sve to ponovo staviti u niz, koji ce biti prosledjen nazad. Na kraju cemo taj niz pomocu iskaza return vratiti nazad. 

function dupliranje_niza($niz)
{
for($indeks_petlje = 0; 
$indeks_petlje < count($niz); 
$indeks_petlje++){

$niz[$indeks_petlje] *= 2;
}
return $niz;
}

Primer 2: prosledjivanje niza u funkciju,  a ona vraca niz sa elementima u kome su svi elementi duplirani.


<?php

$niz = array(1, 2, 3, 4, 5, 6);
$niz = dupliranje_niza($niz);

echo "Ovo su duplirane vrednosti.<br />";

foreach ($niz as $vrednost) {
echo "Vrednost: $vrednost<br />";
}

function dupliranje_niza($niz)
{
for($indeks_petlje = 0; 
$indeks_petlje < count($niz); 
$indeks_petlje++){

$niz[$indeks_petlje] *= 2;
}
return $niz;

}

?>

Rezultat:

Ovo su duplirane vrednosti.
Vrednost: 2
Vrednost: 4
Vrednost: 6
Vrednost: 8
Vrednost: 10
Vrednost: 12


Objasnjenje: prosledili smo niz sa elementima 1, 2, 3, 4, 5, i 6. Funkcija je duplirala svaki element i vratila niz.

If you need a function to return the entire array, use the return statement.

Example, if you need a function that doubles the value in array, which is called array_duplication. First we will pass parameter (of array) to that function. Then we will in the body of the function, with the help of loop go through all the elements, duplicating them and all that again put in an array, which will be passed back. Finally, we will, return back that array with the help of return statement.

function array_duplication($array)
{
for($loop_index = 0; 
$loop_index < count($array); 
$loop_index++){

$array[$loop_index] *= 2;
}
return $array;

}

Example 2: passing an array to a function, and that function returns an array with elements in which all elements are duplicated.

<?php

$array = array(1, 2, 3, 4, 5, 6);
$array = array_duplication($array);

echo "These are duplicate values.<br />";

foreach ($array as $value) {
echo "Value: $value<br />";
}

function array_duplication($array)
{
for($loop_index = 0; 
$loop_index < count($array); 
$loop_index++){

$array[$loop_index] *= 2;
}
return $array;

}

?>

Result:

These are duplicate values.
Value: 2
Value: 4
Value: 6
Value: 8
Value: 10
Value: 12



Explanation: we passed array with the elements 1, 2, 3, 4, 5, and 6. The function duplicated each element and returned the array.

No comments:

Post a Comment

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