views:

69

answers:

6

I'm trying to loop through an array backwards, so I figured I could try

$Array = Array("One", "Two", "Three", "Four", "Five");
For ($Entry = Amount_of_values($Array); $Entry = 0; $Entry = $Entry-1){
    Echo $Array[$Entry] . " "; //Should be Five Four Three Two One
}

but I have no idea how to retrieve the amount of values in an array ( *Amount_of_values($Array)* in the example). What's the function I'm looking for?

Thanks in advance!

Edit: Little additional question: why should it be $Entry >= 0 in the for loop, isn't the last thing I want to output $Array[0]?

+5  A: 

You're looking for count:

print count($Array);
Joe
+1  A: 

This will do what you want:

count($array);
Chris
+1  A: 

use count() php function

Haim Evgi
+1  A: 

This should work:

count($Array) 
cad
...why the downvote?
froadie
Why use the alias instead of the direct function? In other languages, `sizeof` means different things depending upon the data type, so why add the layer of possible confusion (especially since it adds nothing over `count()`... http://us3.php.net/manual/en/function.sizeof.php
ircmaxell
Ok, why did SO not record that edit... The post originally had `sizeof($Array)` instead of `count($Array)`, and that's what my response above is to...
ircmaxell
@ircmaxell - edits aren't recorded if they are within 5 minutes from the initial post (just in case you, or someone else thought it was a bug).
Dominic Rodger
+1  A: 

try count($Array):

For ($Entry = count($Array); $Entry = 0; $Entry = $Entry-1){
        Echo $Array[$Entry] . " "; //Should be Five Four Three Two One
    }
froadie
+4  A: 

There's a better way of doing what your code snippet does - using implode and array_reverse:

$Array = Array("One", "Two", "Three", "Four", "Five");
echo implode(" ", array_reverse($Array)); // Should be Five Four Three Two One

The answer to your actual question though, is if you want to count the number of entries in an array, you want count.

Dominic Rodger
`echo implode(array_reverse($Entries));`, since his original array is the other way round.
janmoesen
@janmoesen - where did `$Entries` come from? Why are you using `implode` without a value for the glue?
Dominic Rodger
Thanks Dominic and Jan for answering the question and providing an alternative.
Chris
@Dominic: oh dear, that missing glue was an oversight on my part. As for `$Entries`, that was the OP's variable. All I wanted to point out was the `array_reverse`, which was there in your answer all along. Man, I think my brain was malfunctioning++.
janmoesen
@janmoesen - ah, no, rest assured your brain is functioning fine. My original answer didn't include `array_reverse`, I added that as an edit within the 5 minute window.
Dominic Rodger