Cep Posted February 22, 2008 Share Posted February 22, 2008 Hello, I have a number 12345, which I want to iterate through to perform an action on each individual unit. For example perform and action on 1, then perform an action on 2, then perform an action on 3 and so on. I tried to use type juggling on the variable containing the value and curly braces at different positions like this (as it says is possible in the PHP manual), <?php $number = 12345; $numlen = strlen($number); for ($i = 0; $i <= $numlen; $i++) { echo $number{$i}; // this should reference the position of the individual number } ?> However I am getting nothing returned. Quote Link to comment Share on other sites More sharing options...
p2grace Posted February 22, 2008 Share Posted February 22, 2008 Try this, also I'm not sure why you'd want to be echoing the number as well so you might want to remove that part. <?php $number = 12345; $numlen = strlen($number); for ($i = 0; $i <= $numlen; $i++) { echo "$number $i"; // this should reference the position of the individual number } ?> Quote Link to comment Share on other sites More sharing options...
Cep Posted February 22, 2008 Author Share Posted February 22, 2008 I don't think you understand what I was trying to do. The result I expect to see is 12345 and if I changed the line slightly to echo $number{$i}."<br />"; I would expect to see, 1 2 3 4 5 Quote Link to comment Share on other sites More sharing options...
aschk Posted February 22, 2008 Share Posted February 22, 2008 You can't iterate through a number, there's no such thing. You CAN iterate through a string... e.g. <?php $number = (string)12345; $numlen = strlen($number); for ($i = 0; $i <= $numlen; $i++) { echo $number{$i}; // this should reference the position of the individual number } ?> Quote Link to comment Share on other sites More sharing options...
aschk Posted February 22, 2008 Share Posted February 22, 2008 Incidently enclosing variables inside double inverted commas (") in PHP causes the variable to be interpreted, whereas if you concatenated the variable to the " string it'll will do any array (which is essentially what the {} mean for a string) referencing that is needed. Hence, "$number{$i}" , to PHP means, i have a string, interpret variable $number, then interpret variable $i, $number = 12345, $i=0 (on 1st run), so it gives you 123450 On the other hand, if you did $number{$i}."" , to PHP means, i have a variable to be concatenated, that variable is $number{$i} , I know i'm working with an string (as array) so i'll find that array value and concatenate it with the string. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.