Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to access and return specific value of a foreach in PHP?
In PHP, you can access and modify array values within a foreach loop by using a reference operator (&). This allows you to directly modify the original array elements during iteration.
Syntax
The basic syntax for accessing values by reference in foreach is ?
foreach ($yourArrayName as &$anyVariableName) {
// Modify $anyVariableName to change original array
}
Example
Let's multiply each array value by 5 using foreach with reference ?
<?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>";
}
?>
175 250 500 375
Key Points
When using references in foreach loops:
- The
&operator creates a reference to the original array element - Changes made to
$tempValuedirectly modify the original array - Always unset reference variables after the loop to avoid unexpected behavior
Conclusion
Using references in foreach loops allows direct modification of array values. This is particularly useful when you need to transform array data in-place or return specific modified values.
Advertisements
