lara336223's avatar

Iterate though a while loop & an array

Hello, I have an array that is 12 in length. In my loop I have $i <= 12 so I want to get my script to show the Text in my array using the $i++, I think :~/ Can anyone help please ? Thank-You Sid

0 likes
3 replies
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

Certainly! If you have an array with 12 elements and you want to iterate through it using a while loop, you can do the following:

<?php

$texts = [
    'Text 1',
    'Text 2',
    'Text 3',
    'Text 4',
    'Text 5',
    'Text 6',
    'Text 7',
    'Text 8',
    'Text 9',
    'Text 10',
    'Text 11',
    'Text 12',
];

$i = 0;
while ($i < count($texts)) {
    echo $texts[$i] . "<br>";
    $i++;
}

Explanation:

  • Use $i = 0 to start at the first element (arrays are zero-indexed).
  • The loop condition should be $i < count($texts) to avoid going out of bounds.
  • Inside the loop, access each element with $texts[$i].
  • Increment $i with $i++ after each iteration.

Let me know if you need further clarification!

Snapey's avatar

if you were coding php 3 you might do this,

Most would use a foreach loop. However Lary just gives you what you ask it.

Please or to participate in this conversation.