Manipulate for loop to run code with specific variables only PHP?

In PHP, you can manipulate a for loop to execute specific logic based on variable values using conditional statements. This allows you to process array elements differently based on certain criteria.

Let's say we have an array of marks and want to modify values less than 40 by doubling them, while keeping other values unchanged ?

<?php
$marks = [45, 67, 89, 34, 98, 57, 77, 30];

echo "Original marks: ";
print_r($marks);

echo "\nProcessed marks:<br>";
foreach($marks as $mark) {
    if($mark < 40) {
        $processedMark = $mark * 2;
    } else {
        $processedMark = $mark;
    }
    echo $processedMark . "<br>";
}
?>
Original marks: Array
(
    [0] => 45
    [1] => 67
    [2] => 89
    [3] => 34
    [4] => 98
    [5] => 57
    [6] => 77
    [7] => 30
)

Processed marks:
45
67
89
68
98
57
77
60

Using Traditional For Loop

You can achieve the same result using a traditional for loop with index-based access ?

<?php
$marks = [45, 67, 89, 34, 98, 57, 77, 30];

echo "Processed marks using for loop:<br>";
for($i = 0; $i < count($marks); $i++) {
    if($marks[$i] < 40) {
        echo ($marks[$i] * 2) . "<br>";
    } else {
        echo $marks[$i] . "<br>";
    }
}
?>
Processed marks using for loop:
45
67
89
68
98
57
77
60

Modifying Original Array

If you want to permanently modify the original array, you can use a for loop to update the actual array elements ?

<?php
$marks = [45, 67, 89, 34, 98, 57, 77, 30];

echo "Original array: ";
print_r($marks);

// Modify the original array
for($i = 0; $i < count($marks); $i++) {
    if($marks[$i] < 40) {
        $marks[$i] = $marks[$i] * 2;
    }
}

echo "Modified array: ";
print_r($marks);
?>
Original array: Array
(
    [0] => 45
    [1] => 67
    [2] => 89
    [3] => 34
    [4] => 98
    [5] => 57
    [6] => 77
    [7] => 30
)
Modified array: Array
(
    [0] => 45
    [1] => 67
    [2] => 89
    [3] => 68
    [4] => 98
    [5] => 57
    [6] => 77
    [7] => 60
)

Conclusion

You can manipulate for loops in PHP using conditional statements to process specific array elements differently. Use foreach for simple iteration or traditional for loops when you need index-based modifications of the original array.

Updated on: 2026-03-15T09:32:50+05:30

304 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements