Variables in PHP Array? - php

So i have the code below basically when its run it will display a graph. How can i make the variables inside the arrays work the variable works and when echoed will give a number but for some reason it doesn't input number there. $mar1 in [here]
$lineChart = new gLineChart($_GET['width'],$_GET['height']);
[here]$lineChart->addDataSet(array($mar1,315,66,40));[/here]
$lineChart->setLegend(array("first"));
$lineChart->setColors(array("ff3344", "11ff11", "22aacc", "3333aa"));
$lineChart->setVisibleAxes(array('x','y'));
$lineChart->setDataRange(30,400);
$lineChart->addAxisLabel(0, array("This", "axis", "has", "labels!"));
$lineChart->addAxisRange(1, 30, 400);
$lineChart->setGridLines(0, 15);
$lineChart->renderImage();

This is a very, very basic question about PHP syntax. Arrays can and frequently are used with variable data.
There isn't anything wrong with the syntax of the code that you posted, so chances are that this is a case of the $mar1 variable not being defined or not containing the data that you're expecting. You probably want to echo or var_dump this variable and see what's in it and work backwards from there.
If $mar1 doesn't contain what you expect, look in the code above that line and see if its value is being set. If this is being passed in the browser's query string like the $_GET['width'] and $_GET['height'] variables are, you would need to access it as $_GET['mar1'] instead of just $mar1.
If this file is being included from another file or includes/requires other files, it could also be defined in the including file(s).
If $mar1 does contain the value you're expecting, then check the documentation for the gLineChart class and make sure that you're passing it all the correct parameters.

Related

Is it valid in php to compare the value

$newOrders is an array and contains order objects...
order_id is an objects variable. I want to compare the order_id value to another variable($orderId) in If loop...
but it fails
Here is my code:
if($newOrders[$i]->order_id == $orderId){
echo "voila, found it:".$newOrders[$i]."<br>";
return $newOrders[$i];
}
Whenever I come across a piece of code that does not work - especially comparisons - I print out both sides of the variables (and often break down more complex variables, like your array) and actually look at the information, rather than assume I know from looking at the code.
It is inevitably a problem that is obvious as to what is wrong when the data is dumped out or otherwise manually examined. Tools such as Symfony VarDumper or just print_r, or an IDE with breakpoints and variable inspection are all suitable to see exactly what is going on.
Are you sure this array contains object, have you checked? If yes, then how ?
What is the variable $i there, could you please put full code (I believe snippet should be in some loop for or foreach)
You can always check for a valid object of a class by
if ($newOrders[$i] instanceof Order) { //Presuming Order is your class name
//do your stuff
}
You can also check by using var_dump() function to check the variables inside the object.
I hope it'll help.

What is the proper name for accessing an object property by string?

I've been searching for quite a while and cannot find what this method is actually called.
In PHP example:
$var->{'property_name'}
Depending on what you are accessing it will be called...
A variable variable
A variable property
A variable function
It is worth noting that the curly-braces are only needed when you need to disambiguate an expression (bear in mind the string you use may itself be stored in a variable!)
And so on. This is documented in the PHP manual for variable variables.

Best method to recognize unused variables

I have code where I use some variables. Example:
$name = "someName";
$output = sprintf($doingText, $name); // $doingText is here undefined
I want to search the code for surely undefined variables (some sort of static code analysing).
These variables should be all some language text. No problem until there, but I don't want to make manually a list which variables exist: I want to get the variable names and then make some html form where I can see them and put into database in variablename-text pairs.
Question is: how to search them? (I haven't found any script which is able to do this in PHP by googling...)
(p.s.: I don't know what is the best method to search them as there may not be only assignments by =, but also with foreach ($arr as $val) etc.)
Why not use an IDE like NetBeans? That will actively check if you have unused variables. So while your coding it will show you in real time, rather then finish the script and find out you have x amount of errors/unused variables. Just food for thought.

Defining constants with $GLOBALS

I want to use a global variable setup where they are all declared, initialized and use friendly syntax in PHP so I came up with this idea:
<?
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
$GLOBALS['debugger'] = 1; // set $GLOBALS['debugger'] to 1
DEFINE('DEBUGGER','$GLOBALS["debugger"]'); // friendly access to it globally
echo "1:" . DEBUGGER . ":<br>";
echo "2:" . ${DEBUGGER}. ":<br>";
echo "3:" . $GLOBALS['debugger'] . ":<br>";
if (DEBUGGER==1) {echo "DEBUG SET";}
?>
generates the following:
1:$GLOBALS["debugger"]:
Notice: Undefined variable: $GLOBALS["debugger"] in /home/tra50118/public_html/php/test.php on line 8
2::
3:1:
How can there be an error with 2: when clearly $GLOBALS["debugger"] IS defined? And then not generate a similar notice with the test at line 10?
I think what I am trying to do is to force PHP to interpret a string ($GLOBALS["debugger"]) as a variable at run time i.e. a constant variable variable
Disclaimer: I agree with the comments, globals are generally a bad idea.
That said, there's a few questions here that are worth answering, and the concept of indirection is useful, so here goes.
${'$GLOBALS["debugger"]'} is undefined. You don't include the leading '$' when using indirection. So, the correct version would be define('DEBUGGER', 'GLOBALS["debugger"]').
But, this doesn't work either. You can only access one level down via indirection. So you can access the array $GLOBALS, but you can't access keys in that array. Hence, you might use :
define('DEBUGGER', 'debugger');
${DEBUGGER};
This isn't useful, practically. You may as well just use $debugger directly, as it's been defined as a global and will be available everywhere. You may need to define global $debugger; at the start of functions however.
The reason your if statement is not causing notices is because you defined DEBUGGER to be a string. Since you aren't trying to use indirection in that line at all, it ends up reading as:
if ("$GLOBALS['debugger']"==1) {echo "DEBUG SET";}
This is clearly never true, though it is entirely valid PHP code.
I think you may have your constants crossed a bit.
DEFINE('DEBUGGER','$GLOBALS["debugger"]'); sets the constant DEBUGGER to the string $GLOBALS["debugger"].
Note that this is neither the value nor the reference, just a string.
Which causes these results:
1: Output the string $GLOBALS["debugger"]
2: Output the value of the variable named $GLOBALS["debugger"]. Note that this is the variable named "$GLOBALS["debugger"]", not the value of the key "debugger" in the array $GLOBALS. Thus a warning occurs, since that variable is undefined.
3: Output the actual value of $GLOBALS["debugger"]
Hopefully that all makes sense.
OK, thanks to all who answered. I think I get it now, I am new to PHP having come form a C++ background and was treating the define like the C++ #define and assuming it just did a string replace in the precompile/run phase.
In precis, I just wanted to use something like
DEBUGGER = 1;
instead of
$GLOBALS['debugger'] = 1;
for a whole lot of legitimate reasons; not the least of which is preventing simple typos stuffing you up. Alas, it appears this is not doable in PHP.
Thanks for the help, appreciated.
You can not use "variable variables" with any of the superglobal arrays, of which $GLOBALS is one, if you intend to do so inside an array or method. To get the behavior you would have to use $$, but this will not work as I mentioned.
Constants in php are already global, so I don't know what this would buy you from your example, or what you are going for.
Your last comparison "works" because you are setting the constant to a string, and it is possible with PHP's typecasting to compare a string to an integer. Of course it evaluates to false, which might be surprising to you, since you expected it to actually work.

PHP Passing by reference

Lets assume the following:
private $array = array(/*really big multi-dimensional array*/);
public function &func1($specific_large_sub_array_key)
{
return $this->array[$specific_large_sub_array_key]
}
public function func2()
{
$specificArray = &$this->func1(1);
$this->func3($specificArray);
}
public function func3($specificArray)
{
/* do stuff here*/
}
My question is this:
If func3 does not specify that $specificArray is not passed by reference to it, does PHP make a copy of $specificArray when it calls func3 inside of func2? Or does PHP keep the reference and propagate it automatically?
i.e. Will this...
public function func3($specificArray)
{
unset($specificArray[234]);
}
...affect $array?
Thank you
Note, this example is extremely simplified.
PHP is pretty intelligent as to how it deals with variables and copies.
Take the following example:
// Allocate one variable with content 'Hello'
$var = 'Hello';
At this point, the Zend Engine has a representation of your string variable with the content, Hello.
Now if you do this:
$varCopy = $var;
You have 2 independent variables ($var and $varCopy), but since their contents are the same, the content only exists in one place in memory (basically a true copy hasn't been made yet). At this point, the two variables reference the same value (Hello) in a symbol table. It will only copy the contents once one of the two variables is modified. This same logic works for 2 copies to any number of copies.
Put simply, PHP is smart enough not to copy the value of the variable or array when it isn't necessary to make a copy.
You can learn more about this on the Reference Counting Basics page on the PHP manual. They even give an example specific to arrays towards the end.
A useful function is memory_get_usage which can show you how much memory PHP is using. You can use this to track the fact that the memory usage will change very little as you pass multiple copies of your array around. This can help prove the point outlined in the reference counting basics section of the manual.
You don't need to know all the details about how it works, but do be aware that PHP is smart in how it creates and manages references.
EDIT:
To answer your actual question directly, no, in func3 PHP will not make a copy of the array even if you don't pass it by reference. It will use references as illustrated in the reference counting basics section, so you can pass it by value without any concern.
If you call unset however, the value you unset will only be removed from the local copy of the array, so it ultimately isn't removed from the source array unless you pass it by reference to the function. But passing it by value does not create a whole new copy of the entire gigantic array. Even removing one value from the copy doesn't create a whole new copy minus the entry you removed (you just have a second array with all identical references to the first, but it is missing the one reference to the removed entry).
Can't do multiline comments, so as an answer:
return &$this->array[$specific_large_sub_array_key]
^
But to also give you an answer to your question:
i.e. Will this... [...] ...affect $array?
Plain and simple: No. Reason: It's a different variable, not an alias (reference).

Categories