3

I have the following code:

$page=3;

$i=1;

    while($i<=$pages) {
      $urls .= "'"."http://twitter.com/favorites.xml?page=" . $i ."',";
      $i++;
    }

What I need to create is this array:

$data = array('http://twitter.com/favorites.xml?page=1','http://twitter.com/favorites.xml?page=2','http://twitter.com/favorites.xml?page=3');

How can I produce an array from the while loop?

1

3 Answers 3

6
$urls = array();
for ($x = 1; $x <= 3; $x++) {
    $urls[] = "http://twitter.com/favorites.xml?page=$x";
}

. is for concatenating strings.
[] is for accessing arrays.
[] = pushes a value onto the end of an array (automatically creates a new element in the array and assigns to it).

Sign up to request clarification or add additional context in comments.

6 Comments

+1, however it would be better to retain the $pages variable and use that in the for loop condition
Ain't it supposed to assign an index to the array $urls[$x] = "twitter.com/favorites.xml?page=$x";
@Jeremy no, danits example doesn't suggest this, $url[] will auto assign a key.
@Jeremy, the index is not required, the $urls[] syntax is equivalent to array_push($urls, ....)
I think you need $x inside the string , not $i ?
|
2

You can do:

$page=3;
$i=1;    
$data = array();
while($i <= $page) {
    $data[] = "http://twitter.com/favorites.xml?page=" . $i++;
}

1 Comment

Your url value isn't correct, lose the quotes at each end and the comma, he just wants the URL.
0

Try this instead:

$page=3;

$i=1;
$url=array();

while($i<=$pages) {
    $urls[]="http://twitter.com/favorites.xml?page=".$i ;
    $i++;
}

echo("<pre>".print_r($url,true)."</pre>");

Comments

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.