1

I want to ask pretty simple question (for most of you) but I can't find the solution right now.

We have $names = array('Alex','James','Jack');

I want to use for loop to echo this:

1. Alex
2. James
3. Jack

But I'm using this loop right now which isn't working as I want it to:

for($i = 0; $i <= count($names); $i++) { echo $i.$names[$i]."<br/>"; }

and it's echoing this:

0. Alex
1. James
2. Jack

The problem is because we are starting from 0 because it's an array. If I put a starting point 1 it's missing the first object from the array.

What's the fix for that?

2
  • why not use a foreach loop? same output essentialy just imho easier when used on arrays Commented Jan 3, 2017 at 17:16
  • 2
    Echo $i + 1 instead of $i? If you want to add 1 to a value, + 1 does just that. Commented Jan 3, 2017 at 17:16

1 Answer 1

3

Why not just increment your variable

$names = array('Alex','James','Jack');
for($i = 0; $i <= count($names); $i++) { 
    $j = $i+1;
    echo $j.$names[$i]."<br/>"; 
}
Sign up to request clarification or add additional context in comments.

1 Comment

Because I'm still drunk... Thanks. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.