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...

$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++;

  }

 

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.

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?

You want to use variable variables here:

<?php
$a0 = 'zero';
$a1 = 'one';
$a2 = 'three';
$a3 = 'two';
$a = array();
for($i=0;$i<10;$i++)
   if (isset(${'a'.$i}))
        $a[$i] = ${'a'.$i};
echo '<pre>' . print_r($a,true) . '</pre>';
?>

 

Ken

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.