View Full Version : collect the data from a loop (as one variable)

06-12-2007, 04:53 PM
Hello, im going to take the final test on php tomorrow and im looking through the exercises I got but I have some problem with one.

It says I should create a loop to display a text in reverse and thats kinda easy but I now have to check if its the same as the original text, (for example: anna is anna reversed)

So I a loop but I cant figure out how to use all the letters in the loop as one variable.

This will display the name reversed:

$namn = 'anna';
for($numb = strlen($namn);$numb>=0;$numb--){
$check2 = substr($namn,$numb,1);
echo $check2;

But what can I use the collect all the letters from $check2 as one thing? :)

06-12-2007, 05:06 PM
you are checking to see if the text is a palindrome basically.

create some array to store the new text
use forloop gathering each character into a element
array_reverse() to change the order
implode() the array back into a string
compare original with new.

on a side note you wouldn't by change to go UNH ?

06-12-2007, 05:40 PM
Thanks for the reply, I have never really used arrays, how will I be able to loop the array X numbers of time? foreach only change the all the arrays once right?

PS: I go to school in sweden =)

06-12-2007, 06:04 PM
If you want to do this just using strings, though it will be a bit tedious, you can try:

1. Find the length of the string, using strlen()

2. Use a for loop to loop that many times.

3. In the loop, add $string[$n], where $n is the strlen, descending 1 each time.
Add that to the new variable, so you get $var = $var.$string[$n];

4. After the loop, just check if they match.

06-12-2007, 06:58 PM
Thanks it worked great, I added:
$var = $var . $check2;

Anyways is it better to use arrays? This is just the beginner course so I don't think we're working with arrays but I didn't actually take this course in school so want to be well prepared as I'm only going there for the test.