Jump to content

[SOLVED] Using variable variables for arrays


TheToothlessRebel

Recommended Posts

Using PHP 5.2.9 and the following code:

$test = array(
'name' => "test array",
'job' => "prove syntax"
);

echo $test[name];
echo "<br>";
echo $test[job];
echo "<br>";

$variableName = "test";

echo ${$test}[name];
echo "<BR>";
echo ${$test[name]};

 

I get the following output:

test array

prove syntax

 

However, I expected the second set of echoes to also produce some output, which they are not. I had hoped one of the two syntaxes would have displayed "test array". What am I doing wrong here?

Firstly, remember to quote the array keys: $test['name'] not $test[name]

 

${$test}[name] won't work, 'cause you're trying to access the key name in the array named what $test is containing. Since it's containing an array and not a string, it won't work.

 

${$test[name]} translates to a variable named $test array which is an invalid name (containing a space).

 

Maybe you want this:

 

<?php
$array_name = 'testarray';
$testarray = array(
'name' => 'a name',
'job' => 'a job'
);
echo ${$array_name}['name'];
//outputs 'a name'
?>

OK, I mistyped my simplified code and that explains why it didn't work. It should have been:

$test = array(
'name' => "test array",
'job' => "prove syntax"
);

echo $test[name];
echo "<br>";
echo $test[job];
echo "<br>";

$variableName = "test";

echo ${$variableName}[name];

Although I'll take ye suggestion to heart and quote array keys, this code does work as expected. Which only means in my real code I can't determine why it's not working in the same way. I'm trying to use this in practice, and running into a brick wall. I have two sources:

<?php

/*************************/
/* We need to include a  */
/* few things to start.  */
/*************************/
include('includes/header.php'); // This is the logo and corp name
include('includes/navbar.php'); // The navigation bar
include('includes/min_functions.php'); // List of hard-coded mineral price defaults
include('includes/blueprint_functions.php'); // This is where the data on our blueprints is listed


// Let's start writing the page.
echo "<form method=\"post\">";
	echo "<p>";
		echo "This page is designed for display of corporate pricing of items internally, which is equal to market cost of materials. This serves to establish a";
		echo "'bring your own minerals' approach to BPO usage within the corporation and helps manufacturers determine the viability of a product for market.";
	echo "</p>";
	// Actually perform the function, constructed in min_info.php
	postPrices(1);
	echo "<p>";
		echo "Using this data we can calculate the cost of manufacturing any number of runs for any of the corporation's blueprints.";
		echo "You simply need to provide how many runs of which blueprint you wish to make:";
	echo "</p>";
	// Both these function are in blueprint_functions.php
	selectBlueprint();
	selectRuns();	
	// This button does the magic
	echo "<input type=\"submit\" value=\"Calculate Cost\">";
echo "</form>";
// Debuging
echo "$blueprint ";
echo $runs;
// End Debugging
if ($blueprint) {
	calculateUsage();
}

?>

and

<?php

// This is the info we have on our blueprints

$CapBooster800 = array(
	'name'      => 'Cap Booster 800',
	'id'        => '11290//963878561',
	'isogen'    => 0,
	'megacyte'  => 3,
	'mexallon'  => 228,
	'nocxium'   => 12,
	'pyerite'   => 397,
	'tritanium' => 1356,
	'zydrine'   => 3
);
$hobgoblinI = array(
	'name'      => 'Hobgoblin I',
	'id'        => '2455//1662253731',
	'isogen'    => 4,
	'megacyte'  => 0,
	'mexallon'  => 0,
	'nocxium'   => 2,
	'pyerite'   => 6,
	'tritanium' => 459,
	'zydrine'   => 0
);

// To edit blueprint properties ye need go no further

// Need this for later
$blueprint;
$runs;

function selectBlueprint() {

	global $blueprint;

	if ($_POST["blueprint"]) {
		$blueprint = $_POST["blueprint"];
	} else {
		$blueprint = "None";
	}

	// Here we select the blueprint, $blueprint
	echo "<p>";
	echo "Blueprint: ";
	echo "<select name=\"blueprint\" value=\"$blueprint\">";
		echo "<option value=\"None\">";
			echo "Please Select";
		echo "</option>";
		echo "<option value=\"CapBooster800\">";
			echo "Cap Booster 800";
		echo "</option>";
		echo "<option value=\"hobgoblinI\">";
			echo "Hobgoblin I";
		echo "</option>";
	echo "</select>";
	echo "</p>";

}

// This function allows to set a number of runs, $runs
function selectRuns() {

	global $runs;

	// Check for previous existance:
	if ($_POST["runs"]) {
		$runs = $_POST["runs"];
	}

	// Here we select the runs to perform
	echo "<p>";
	echo " Runs: ";
	if (!$_POST["runs"]) {
		echo "<input name=\"runs\" value=\"1\" size=\"2\" type=\"text\"> ";
	} else {
		echo "<input name=\"runs\" value=\"$runs\" size=\"2\" type=\"text\"> ";
	}
	echo "</p>";
}

// This function calculates the costs for materials and displays them. $display could be full (shows itemized and total cost),
	// itemized (shows only the itemized portion), total (shows only the total cost), or min_only (shows only minerals used,
	// no costs associated)
function calculateUsage($display) {

	global $blueprint, $runs, $isogen_used, $isogen_cost, $megacyte_used, $megacyte_cost;

	// First the math part, calculate two values for each mineral, $X_used for how much is needed and $X_cost for how much it
		// will cost
	$isogen_used = ${$blueprint}['isogen'] * $runs;
	$isogen_cost = $isogen_used * $isogen_current;
	$megacyte_used = ${$blueprint}['megacyte'] * $runs;
	$megacyte_cost = $megacyte_used * $megacyte_current;
	$mexallon_used = ${$blueprint}['mexallon'] * $runs;
	$mexallon_cost = $mexallon_used * $mexallon_current;
	$nocxium_used = ${$blueprint}['nocxium'] * $runs;
	$nocxium_cost = $nocxium_used * $nocxium_current;
	$pyerite_used = ${$blueprint}['pyerite'] * $runs;
	$pyerite_cost = $pyerite_used * $pyerite_current;
	$tritanium_used = ${$blueprint}['tritanium'] * $runs;
	$tritanium_cost = $tritanium_used * $tritanium_current;
	$zydrine_used = ${$blueprint}['zydrine'] * $runs;
	$zydrine_cost = $zydrine_used * $zydrine_current;

	// Now to total them up
	$total_cost = $isogen_cost + $megacyte_cost + $mexallon_cost + $nocxium_cost + $pyerite_cost + $tritanium_cost +
		$zydrine_cost;

	// This is the itemized display portion
	if ($display == "full" || $display == "itemized") {
		echo "<p>";
			if ($isogen_cost != 0) {
				echo "$isogen_cost ISK for $isogen_used isogen. <br />";
			}
			if ($megacyte_cost != 0) {
				echo "$megacyte_cost ISK for $megacyte_used megacyte. <br />";
			}
			if ($mexallon_cost != 0) {
				echo "$mexallon_cost ISK for $mexallon_used mexallon. <br />";
			}
			if ($pyerite_cost != 0) {
				echo "$pyerite_cost ISK for $pyerite_used pyerite. <br />";
			}
			if ($nocxium_cost !=0) {
				echo "$nocxium_cost ISK for $nocxium_used nocxium. <br />";
			}
			if ($tritanium_cost != 0) {
				echo "$tritanium_cost ISK for $tritanium_used tritanium.<br />";
			}
			if ($zydrine_cost != 0) {
				echo "$zydrine_cost ISK for $zydrine_used zydrine.";
			}
		echo "</p>";
	}

	// Display the total cost
	if ($display != "min_only" && $display != "itemized") {
		echo "<p>";
			echo "Total cost is $total_cost ISK.";
			$name = ${$blueprint}['name'];
			echo "For the blueprint ($name) and $runs runs.";
		echo "</p>";
		echo "${$blueprint}['name']";
		echo "$blueprint";
	}

	// Display only the minerals used.
	if ($display == "min_only") {
		echo "<p>";
			if ($isogen_used != 0) {
				echo "$isogen_used isogen";
			}
			if ($megacyte_used != 0) {
				echo "$megacyte_used megacyte";
			}
			if ($mexallon_used != 0) {
				echo "$mexallon_used mexallon";
			}
			if ($nocxium_used != 0) {
				echo "$nocxium_used nocxium";
			}
			if ($pyerite_used != 0) {
				echo "$pyerite_used pyerite";
			}
			if ($tritanium_used != 0) {
				echo "$tritanium_used tritanium";
			}
			if ($zydrine_used != 0) {
				echo "$zydrine_used zydrine";
			}
		echo "</p>";
	}


}

?>

The output of which can be seen at http://arcl.sufferquietly.com/igb/manufacturing.php. It's for the MMORPG EVE, to help me do some math. My issue is that although the variable $blueprint contains the proper value both outside the calculateUsage() function and in, it is not seeming to use it as the variable name for the array. The code post is as it stands now, I'll be going through and quoting the array keys after this post. I know I must be missing something simple!

Thanks, I'll look into printing the variable instead of echo? I need to get that value into the html from php somehow.

 

Then how come the variable $name is also empty? It should have been defined as whatever ${$blueprint}[name] contains.

I found the issue, it just hit me like lightning! The arrays are defined outside the scope of the calculateUsage() function and were not declared global within the function. The function did not have access to the arrays!

 

I cannot find the solved mod button on this forum to mark this post as such.

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.