PHP How to display array values with text “even” to be displayed for even index values

PHPServer Side ProgrammingProgramming

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.

raja
Published on 20-Nov-2020 10:03:35
Advertisements