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
PHP How to display array values with text "even" to be displayed for even index values
In PHP, you can display array values with the text "even" for even index positions using a for loop with conditional logic. This technique checks if an index is divisible by 2 and assigns "Even" text or the actual value accordingly.
Example
The following example creates an array and displays "Even" for even index values ?
<?php
$arrayList = [];
for ($counter = 0; $counter < 5; $counter++) {
($counter % 2 == 0) ? ($arrayList[] = "Even") : ($arrayList[] = $counter);
}
for ($counter = 0; $counter < 5; $counter++) {
echo $arrayList[$counter] . " ";
}
?>
Even 1 Even 3 Even
How It Works
The code uses the modulo operator (%) to check if an index is even. When $counter % 2 == 0 is true (for indices 0, 2, 4), it assigns "Even" to the array. For odd indices (1, 3), it assigns the actual counter value.
Alternative Approach
You can also use an ifâelse statement for better readability ?
<?php
$arrayList = [];
for ($counter = 0; $counter < 5; $counter++) {
if ($counter % 2 == 0) {
$arrayList[] = "Even";
} else {
$arrayList[] = $counter;
}
}
foreach ($arrayList as $value) {
echo $value . " ";
}
?>
Even 1 Even 3 Even
Conclusion
Using the modulo operator with conditional statements allows you to easily identify and replace even index values with custom text while preserving odd index values in PHP arrays.
