Accessing variables in loops eg: $var[$i] etc

Hard one to put into words but what I am looking to do should be understandable by this non working code :slight_smile:


<?

	$_POST[entry07_cash] = "22";
	$_POST[entry08_cash] = "1";
	$_POST[entry09_cash] = "22";
	$_POST[entry10_cash] = "55";
	$_POST[entry11_cash] = "52";
	$_POST[entry12_cash] = "123";
	$_POST[entry13_cash] = "551";
	$_POST[entry14_cash] = "123";
	$_POST[entry15_cash] = "441";
	$_POST[entry16_cash] = "12";
	$_POST[entry17_cash] = "551";
	$_POST[entry18_cash] = "11";

for ($weenumber = 1; $weenumber <= 30; $weenumber++) {

	if ($weenumber == "1") { $weenumber = "01"; }
	if ($weenumber == "2") { $weenumber = "02"; }
	if ($weenumber == "3") { $weenumber = "03"; }
	if ($weenumber == "4") { $weenumber = "04"; }
	if ($weenumber == "5") { $weenumber = "05"; }
	if ($weenumber == "6") { $weenumber = "06"; }
	if ($weenumber == "7") { $weenumber = "07"; }
	if ($weenumber == "8") { $weenumber = "08"; }
	if ($weenumber == "9") { $weenumber = "09"; }
	
	if ($_POST[entry[$weenumber]_cash] != "") {  $_POST[entry[$weenumber]_cash] = number_format($_POST[entry[$weenumber]_cash],2); }	
	
}

?>

How do I access a variable based on another variable so I can run for loops ?

Im completely lost :S

Many thanks for any assistance,

Rik

First of all, if you are making the array yourself by coding then I would recommend to use single or double quotes for index in the array like this:


$_POST['entry07_cash'] = "22"; // instead of $_POST[entry07_cash]

Then reading would be easier something like this:


for ($weenumber = 1; $weenumber <= 30; $weenumber++) { 
	$weenumber = str_pad($weenumber, 2, "0", STR_PAD_LEFT);
	if (isset($_POST["entry{$weenumber}_cash"]) && !empty($_POST["entry{$weenumber}_cash"])){
		echo number_format($_POST["entry{$weenumber}_cash"], 2) . "<br />";
	}     
}

Brilliant thanks!

Can I ask why using single or double quotes on it makes a difference? Just out of interest :slight_smile:

Rik

See the following examples:


define('my_constant' , 'myvalue');
$array[my_constant] = 'yourvalue';
print_r(array_keys($array));

//----------------
error_reporting(E_ALL);
$array['my_array'] = 'test';

What you’re probably not seeing Rikki is that PHP is throwing low level warnings when you leave them out (Undefined constant my_constant; assuming ‘my_constant’)