Jump to content

Quick Question: Add varibles to array via while loop.


cs.punk

Recommended Posts

Ok it works perfectly with :

$count = 0;
$a = array();

while (isset($_POST['a' . $count]))
{$a[] = $_POST['a' . $count];
   $count++;
}

 

But I am trying to do the following

//there are 10 $a varibles each with a leading 0, 1, 2, 3 etc...
//I want them in a array so I can sort them later on
$count = 0;
$a = array();
while (isset($a . $count))
{$a[] = $a . $count;
  $count++;
  }

 

But I keep gettings errors...

Link to comment
Share on other sites

$count = 0;

$a = array();                            // You're defining $a as an array here

while (isset($a . $count))            //  So $a.$count will give "Array0", which doesn't exist, so no loop processing

{$a[] = $a . $count;

  $count++;

  }

 

Link to comment
Share on other sites

You may need to do it in a for loop to get the desired result.  Since there are 10 variables to be stored in array($a), then:

 


$count = 0;
$a = array();

for ($i = 0; $i <= 10; $i++) {
$a[$i] = "$i$count";
$count++;
}

 

Not tested, but each $a[$i] should return whatever string is in $i$count.  The first iteration would be 00, second would be 11, third 22, all the way up to 9 which would become 1010.  Also, the $count++ is in there because your example used it.  It is redundant, and would be the same as using $a[$i] = "$i$i"; on line 5.

Link to comment
Share on other sites

If you're talking about combining the entire array into one variable, i.e. $a[0] = 1, $a[1] = 2, then you could use explode and implode functions.

 

Implode takes all the variables stored in an array and turns it into one variable with each value separated by a delimiter.  For instance, the above imploded:

 

$a = implode(",",$a);
// $a = "1,2"

per http://us.php.net/manual/en/function.implode.php

 

And to retrieve the values out of a variable into an array:

$a = explode(",",$a);
// converts $a to an array of $a[0]=1, $a[1]=2

 

Is this what you mean?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.