How to access and return specific value of a foreach in PHP?


You can use the below syntax to access the value of a foreach.

The syntax is as follows −

foreach ($yourArrayName as &$anyVariableName)

Let’s say we have the following array:

$values= array(35, 50, 100, 75);

We will now multiple each array value with 5 using the following PHP code −

Example

 Live Demo

<!DOCTYPE html>
<html>
<body>
<?php
$values= array(35, 50, 100, 75);
function getValues($values) {
   $allValues=[];
   $counter=0;
   foreach ($values as &$tempValue) {
      $tempValue = $tempValue * 5;
      $allValues[$counter]=$tempValue;
      $counter++;
   }
   return $allValues;
}
$result=getValues($values);
for($i=0;$i<count($result);$i++){
   echo $result[$i],"<br>";
}
?>
</body>
</html>

Output

175
250
500
375

Updated on: 12-Oct-2020

849 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements