Alright I seem to have a misconception with variable scope with PHP, forgive my lack of the subject as I come from a Java, C# background. Thinking I could make variables accessible to functions or if statements simply by placing it outside it. Below is a snippet of what I'm trying to accomplish:
foreach ($nm as $row=>$im) {
$itm_name = $im;
$lnk = $lnk_cty[$row];
if($mode == 'addMenu') {
$m = $m_id; //id will be coming from fresh insert of menu_name
} else {
$m = $_POST['mnu_add'][$row];
echo "MENU_ID: ".$m;
}
if($mode == 'addCat') {
$m = $c_id; //id will be coming from fresh insert of cat_name
} else {
$m = $_POST['cat_add'][$row];
}
//used for testing purposes
echo "item name: ".$itm_name ."<br />";
echo "lnk: ".$lnk ."<br />";
echo "m: ".$m ."<br />"; //$m is empty here, because its a new declaration as oppose to accessing $m value from if statement
$display_fields .= "<li>".$itm_name." ".$item."</li>";
$sql_array[] = '("' . $itm_name . '", "' . $lnk . '", ' . $m . ')'; // Add a new entry to the queue
}
Now what I'm trying to do is make the $m
variable values accessible outside the if statements its in to the $m
variable used in the $sql_array[]
statement. In C# I would simply declare a variable outside the foreach loop and be able to use it. After doing some reading on the matter I found that using the global or GLOBALS keywords would only work if my global scope variable is assign the value before the foreach, and declaring global $m
to obtain that value within the loop. But with my current code $m
is of a local scope within the if statements and everyone discourages using them. Now, is there a better method of making $m
accessible to the $sql_array[]
statement?
Its true that if statements does NOT have scope , but It seems that there is a problem with the Scope (piece of code in braces)..in the below code snippet the expected result is : $z[0] = 0, $z[1] = 1 but the Actual output obtained is $z[0] = 100; and $z[1] is undefined. The PHP used is from Apache Friends distribution
If
statement blocks do not have their own scope. Whatever data you are assigning to$m
must be empty to begin with. Try debugging things like your$_POST
variables. Also, where is$m_id
being defined? Maybe it is empty as well.PHP does have scope inside functions, class methods and the like. But
if
statements do not have their own scope. For example, the following code would echoHi there!
:Have a read in the manual.