Display Array Values with Text for Even Indexes in PHP



For this, you can use for loop along with some conditions.

The PHP code is as follows −

Example

 Live Demo

<!DOCTYPE html>
<html>
<body>
<?php
   $arrayList = [];
   for ($counter = 0; $counter < 5; $counter++) {
      ($counter%2) ? ($arrayList[] = $counter) : ($arrayList[] = "Even");
   }
   for ($counter = 0; $counter < 5; $counter++) {
      echo $arrayList[$counter]," ";
   }
?>
</body>
</html>

Output

Even 1 Even 3 Even

Above, for 0th index, the text “Even” is displayed and the same goes on for 2th and 4th index.

Updated on: 2020-11-20T05:34:16+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements