How can I change this function so that I can pass an additional argument. It should multiply each value in the array

How can I change this function so that I can pass an additional argument. It should multiply each value in the array by this additional argument (‘factor’ inside the function).

For ex: $first = array(5,23,10,8,7). When you say…

$second = multiply($first, 3);
var_dump($second);
this should dump $second which contains [15, 69, 30, 24, 21].

This is my code:

<?php

$first = array(5,23,10,8,7);

$second = array();

function show_array($first){

    echo '<b>The values inside the $first array are: </b><br>';

    foreach($first as $value){

       echo $value."<br>";

    }

}

function multiply($first){

    $second = array();

    

    echo "<b>The products multiplied by 5 are: </b><br>";

    $multiplier = 5;

    

    foreach($first as $value){

        $product = $value*$multiplier;

        echo $product."<br>";

        array_push($second,$product);       

    }

    echo '<br><b>The values inside the $second array are:<b>';

    var_dump ($second);      

}

echo show_array($first)."<br>";

$second = multiply($first);

?>

how can I make this post’s code appear readable?

Either use bbcode [code][/code] tags or three markdown back-ticks ``` before/after the lines of code. I have edited your post above to add bbcode tags.

1 Like
$first = array(5,23,10,8,7);
$second = array();

function show_array($first){
	echo '<b>The values inside the $first array are: </b><br>';
	foreach($first as $value){
	   echo $value."<br>";
	}
}

function multiply($first, $multiplier){
	$second = array();			

	echo "<b>The products multiplied by $multiplier are: </b><br>";
	foreach($first as $value){
		$product = $value*$multiplier;
		echo $product."<br>";
		array_push($second,$product); 
	}

	echo '<br><b>The values inside the $second array are:<b>';
	var_dump ($second);      
}

echo show_array($first)."<br>";
$second = multiply($first, 3);
Sponsor our Newsletter | Privacy Policy | Terms of Service