Richard Jones Richard Jones - 6 days ago 5
PHP Question

How to pass array element by reference in PHP?

I want to multiply all my array element with 5,but my code give output 55555.Output should be 5 10 15 20 25.How to handle this?

<?php

function multi($ar,$multiplier){
$i=0;
while($i<count($ar)){
$ar[$i]*=$multiplier;
echo $ar[0];
$i++;
}
}
$arr = array(1,2,3,4,5);
multi($arr,5);
?>

Answer

Here, this will output what you want. It is also stored in another array called outarr, you can use that further.

<?php 
$arr = array(1,2,3,4,5);
$outarr = [];
foreach($arr as $piece){
    $output = $piece * 5;
    array_push($outarr,$output);
    echo $output."<br>";
}
?>

In case you want it function whise:

<?php 
function multi($array,$times = 5){
    foreach($array as $piece){
        $output = $piece * $times;
        array_push($outarr,$output);
        //echo $output."<br>";
    }
    return $outarr;
}

$arr = array(1,2,3,4,5);
multi($array);
var_dump(multi($array));
?>
Comments