Array as parameter (PHP) : Error :Undefined variable - php

I'm trying to call a function and pass an array and other variables to it. this is the code I use to do that :
function fnGetElementsById($ArrCols, $tableName, $id) {
while($arrCols[$i])
{
if($i != 0)
{
$sql = $sql.',';
}
$sql = $sql.$arrCols[$i].' ';
$i++;
} }
the while line is the error or notice line and when I test with var_dump, the array is empty.
the calling code :
$arrCols = array(
0=>'marque',
1=>'prix'
);
$CDB->fnGetElementsById($arrCols, 'Portables', $_POST['id1']);
thank you

You haven't defined $i before the while loop is invoked. Therefore you are basically trying this:
while($arrCols[null]) {
Also your parameter is $ArrCols and the variable name in the while conditional is $arrCols (lowercase first letter).
You need to fix both of these.

You have a case issue.
function fnGetElementsById($ArrCols, $tableName, $id) {
while($arrCols[$i])
Should be
function fnGetElementsById($arrCols, $tableName, $id) {
while($arrCols[$i])
Notice change from ArrCols to arrCols.
Also you did not initialize your $i variable.
Please set it to 0 before using.

Related

Php class property get and set

I have the following codes.
<?php
class Reg {
private $pros = array();
public function __set($key,$val) {
$this->pros($key)= $val;
}
public function __get($key) {
return $this->pros($key);
}
}
$reg= new Reg;
$reg->tst="tst";
echo $reg->tst;
?>
But when executing this script I got the error following.
Fatal error : can't use method return value in write context in line 5
I believe that to add an element to array is possible like the above.
$array = array();
$array('key')='value';
Please make clear that I was wrong.
Thanks
The is because of you are trying to set a functions return value. $this->pros($key) means calling pros($key) function. Not setting a value to $pros array.
The syntax is wrong. Setting values to array be -
$array['index'] = 'value';
Change
$this->pros($key)= $val; -> $this->pros[$key]= $val;
and
return $this->pros[$key];
Working code
$this->pros[$key] = $value;
OR
$keys = array($key);
$this->pros = array_fill_keys($keys,$value);
The array_fill_keys() function fills an array with values, specifying keys.
Syntax:
array_fill_keys(keys,value);

Unexpected Result from User Defined Function - PHP

I'm trying to write a simple function which takes two arguments, adds them together and returns the result of the calculation.
Before performing the calculation the function checks whether either of the two arguments are undefined and if so, sets the argument to 0.
Here's my function:
Function - PHP
function returnZeroAdd ($arg, $arg2)
{
if(!isset($arg))
{
$arg = 0;
}
if(!isset($arg2))
{
$arg2 = 0;
}
echo $arg + $arg2;
}
I've tried to execute it like so :
returnZeroAdd($bawtryReturnCount, $bawtryFReturnCount);
But this throws up an undefined variable $bawtryFReturnCount error.
I do not know why the function isn't setting $bawtryFReturnCount) to 0 before performing the calculation thereby negating the 'undefined variable' error.
Can anybody provide a solution?
You cannot do this the way you want. As soon as you use an undefined variable, you will get this error. So the error doesn't occur inside your function, but already occurs in the call to your function.
1. Optional parameters
You might make a parameter optional, like so:
function returnZeroAdd ($arg = 0, $arg2 = 0)
{
return $arg + $arg2;
}
This way, the parameter is optional, and you can call the function like this:
echo returnZeroAdd(); // 0
echo returnZeroAdd(1); // 1
echo returnZeroAdd(1, 1); // 2
2. By reference
But I'm not sure if that is what you want. This call will still fail:
echo returnZeroAdd($undefinedVariable);
That can be solved by passing the variables by reference. You can then check if the values are set and if so, use them in the addition.
<?php
function returnZeroAdd (&$arg, &$arg2)
{
$result = 0;
if(isset($arg))
{
$result += $arg;
}
if(isset($arg2))
{
$result += $arg2;
}
return $result;
}
echo returnZeroAdd($x, $y);
Note that you will actually change the original value of a by reference parameter, if you change it in the function. That's why I changed the code in such a way that the parameters themselves are not modified. Look at this simplified example to see what I mean:
<?php
function example(&$arg)
{
if(!isset($arg))
{
$arg = 0;
}
return $arg;
}
echo example($x); // 0
echo $x // also 0
Of course that might be your intention. If so, you can safely set $arg and $arg2 to 0 inside the function.
The error is not thrown by the function itself, as the function is not aware of the global scope. The error is thrown before even the function is executed, while the PHP interperter is trying to pass $bawtryFReturnCount to the function, one does not find it, and throws error, however, it's not a fatal one and the execution is not stopped. THerefore, the function is executed with a non-set variable with default value of null, where I guess, isset will not work, as the arguments are mandatory, but not optional. A better check here will be empty($arg), however the error will still be present.
Because the functions are not and SHOULD NOT be aware of the global state of your application, you should do these checks from outside the functions and then call it.
if (!isset($bawtryReturnCount)) {
$bawtryReturnCount = 0
}
returnZeroAdd($bawtryReturnCount);
Or assign default values to the arguments in the function, making them optional instead of mandatory.
Your function could be rewritten as:
function returnZeroAdd ($arg = 0, $arg2 = 0)
{
echo $arg + $arg2;
}
You missunderstand how variables work. Since $bawtryFReturnCount isn't defined when you call the function; you get a warning. Your isset-checks performs the checks too late. Example:
$bawtryReturnCount = 4;
$bawtryFReturnCount = 0;
returnZeroAdd($bawtryReturnCount, $bawtryFReturnCount);
Will not result in an error.
If you really want to make the check inside the function you could pass the arguments by reference:
function returnZeroAdd (&$arg, &$arg2)
{
if(!isset($arg))
{
$arg = 0;
}
if(!isset($arg2))
{
$arg2 = 0;
}
echo $arg + $arg2;
}
However this will potentially modify your arguments outside the function, if it is not what you intend to do then you need this:
function returnZeroAdd (&$arg, &$arg2)
{
if(!isset($arg))
{
$localArg = 0;
}
else
{
$localArg = $arg;
}
if(!isset($arg2))
{
$localArg2 = 0;
}
else
{
$localArg2 = $arg2;
}
echo $localArg + $localArg2;
}
You can now pass undefined variables, it won't throw any error.
Alternatively you might want to give a default value to your arguments (in your case 0 seems appropriate):
function returnZeroAdd ($arg = 0, $arg2 = 0)
{
echo $arg + $arg2;
}
You have to define the variable before pass it to an function. for example
$bawtryReturnCount=10;
$bawtryFReturnCount=5;
define the two variable with some value and pass it to that function.
function returnZeroAdd ($arg=0, $arg2=0)
{
echo $arg + $arg2;
}
if you define a function like this means the function takes default value as 0 if the argument is not passed.
for example you can call the functio like this
returnZeroadd();// print 0
returnZeroadd(4);// print 4
returnZeroadd(4,5);// print 9
or you can define two variables and pass it as an argument and call like this.
$bawtryReturnCount=10;
$bawtryFReturnCount=5;
returnZeroadd($bawtryReturnCount, $bawtryFReturnCount);

PHP Error: Cannot use a scalar value as an array... However

I'm currently working with the medoo.php framework, and although I would normally use their ticket area on github, it appears that no one actually uses that... so...
At any rate, when I'm running one of my files which uses "require" to call the framework, I get the following error:
Warning: Cannot use a scalar value as an array in /home/..../public_html/projects/friendcodes/medoo.min.php on line 759
However, when I inspect the code (the below is lines 752 to 764), I see that it is in fact supposed to check if $where is not set, and if it isn't, make it an array - however this php error begs to differ.
I'm guessing that $where is being set as a variable somewhere else, that's not an array, but there are over 100 occurrences of the variable in the framework, and 830 lines of code, which you probably don't want to see. (Let me know in a comment and I'll add it - again, this is directly from medoo's most two recent updates/releases.)
public function get($table, $columns, $where = null)
{
if (!isset($where))
{
$where = array();
}
$where['LIMIT'] = 1;
$data = $this->select($table, $columns, $where);
return isset($data[0]) ? $data[0] : false;
}
My main question is - How do I rectify this problem without breaking something in this framework which is extremely complex (for my level, at any rate)
Update: How silly of me! I found the problem. Just as people suggested, I was calling $where wrong.
I was calling it with:
$accountinfo = $database->get('xf_user_field_value', ['field_value'], 1);
Instead of
$accountinfo = $database->get('xf_user_field_value', ['field_value'], ["user_id"=>1]);
(Where the third arg is $where) Thanks for the help guys!
Right, first things first, we need to find out what is calling get that shouldn't be. WHICH IS THE ENTIRE PROBLEM. The problem isn't the function itself, the problem is something is calling it using an argument for $where which isn't an array. Changing a library to fix one faulty call is ridiculous.
Step 1: Temporarily edit the get function to include a print_r of the $where variable.
public function get($table, $columns, $where = null)
{
if(isset($where)) print_r($where);
if (!isset($where))
{
$where = array();
}
$where['LIMIT'] = 1;
$data = $this->select($table, $columns, $where);
return isset($data[0]) ? $data[0] : false;
}
This will show us before the error prints the value of $where, which will help you find the malformed get call.
If this fails, try using PHP's built-in backtrace to try to find the issue:
public function get($table, $columns, $where = null)
{
if(isset($where)) print_r(debug_backtrace());
if (!isset($where))
{
$where = array();
}
$where['LIMIT'] = 1;
$data = $this->select($table, $columns, $where);
return isset($data[0]) ? $data[0] : false;
}
The ->get() method is not called properly.
Cannot use a scalar value as an array
That warning is shown if $where is either true, a numeric value or a resource. Valid method calls include:
->get('table', '*')
->get('table', '*', array('WHERE' => 'foo = "bar"'))
Check the manual and fix your code.
EDIT 3: try moving $where['LIMIT'] = 1; inside of the isset statement, since you wouldn't want to pass LIMIT 1 to the query constructor if $where is passed by reference.
DISCLAIMER I have no knowledge of the medoo framework.
public function get($table, $columns, $where = null)
{
if (is_null($where))
{
$where = array('LIMIT'=>1);
}
$data = $this->select($table, $columns, $where);
return isset($data[0]) ? $data[0] : false;
}

array_search wrong argument datatype

I am playing around with this:
$sort = array('t1','t2');
function test($e){
echo array_search($e,$sort);
}
test('t1');
and get this error:
Warning: array_search(): Wrong datatype for second argument on line 4
if I call it without function like this, I got the result 0;
echo array_search('t1',$sort);
What goes wrong here?? thanks for help.
Variables in PHP have function scope. The variable $sort is not available in your function test, because you have not passed it in. You'll have to pass it into the function as a parameter as well, or define it inside the function.
You can also use the global keyword, but it is really not recommended. Pass data explictly.
You must pass the array as a parameter! Because the functions variables are different from globals in php!
Here is the fixed one:
$sort = array('t1','t2');
function test($e,$sort){
echo array_search($e,$sort);
}
test('t2',$sort);
You cannot directly access global variables from inside functions.
You have three options:
function test($e) {
global $sort;
echo array_search($e, $sort);
}
function test($e) {
echo array_search($e, $GLOBALS['sort']);
}
function test($e, $sort) {
echo array_search($e, $sort);
} // call with test('t1', $sort);
take the $sort inside the function or pass $sort as parameter to function test()..
For e.g.
function test($e){
$sort = array('t1','t2');
echo array_search($e,$sort);
}
test('t1');
----- OR -----
$sort = array('t1','t2');
function test($e,$sort){
echo array_search($e,$sort);
}
test('t1',$sort);

PHP function won't execute when called

I'm having a problem with this function. It's supposed to echo out some stuff, but for some reason it won't do so when I call it.
Here's the function:
$count = count($info['level']);
function displayInfo()
{
for ($i=0; $i<$count; $i++)
{
echo "[b]".$info['name'][$i]."[/b]\n\n"
."Level: ".$info['level'][$i]
."\nPrice: ".$info['price'][$i]
."\nSellback: ".$info['sell'][$i]
."\nLocation: ".$location
."\n\nType: ".$info['type'][$i]
."\nElement: ".$info['element'][$i]
."\nDamage: ".$info['damage'][$i]
."\nBTH: ".$info['bth'][$i]
."\n\nSPECIAL"
."\nHits: ".$info['hits'][$i]
."\nType: ".$info['stype'][$i]
."\nElement: ".$info['selement'][$i]
."\nDamage: ".$info['sdamage'][$i]
."\nBTH: ".$info['sbth'][$i]
."\nRate: ".$info['rate'][$i]
."\n\nDescription\n".$description
."\n".$img
."\n\n\n";
}
}
And here's the code I use to call the function:
<?PHP
displayInfo();
?>
I can't find out what's wrong--it's not a sintax error, page loads without interuption.
Thanks in advance.
You are declaring the $count and $info variable outside of your function :
// $info already exists
$count = count($info['level']); // and $count is initialized here
function displayInfo()
{
for ($i=0; $i<$count; $i++)
...
In PHP, a variable declared outside of a function is not visible from inside the function.
If you want your "external" variables to be visible from inside the function, you have to declare them as global in the function :
$count = count($info['level']);
function displayInfo()
{
global $count, $info;
// $count is now visible ; same for $info
for ($i=0; $i<$count; $i++)
...
But it's generally considered better to pass the variables as parameters to the function : you have to declare them as a parameter :
function displayInfo($count, $info)
{
for ($i=0; $i<$count; $i++)
...
And pass them to the function when calling it :
$count = count(...);
displayInfo($count, $info);
Passing parameters instead of using global variables ensures you know what your functions have access to -- and modify.
Edit : thanks for the note, X-Istence ! Didn't read enough of the given code :-(
$count and $info are declared outside the function and therefore they are not visible within it. You could pass $info into the function and then calculate $count within, like this:
//get info from db, or somewhere
$info = array();
displayInfo($info);
function displayInfo($info)
{
$count = count($info['level']);
//now $count and $info are visible.
}
See http://php.net/manual/en/language.variables.scope.php
Add global for variables which should be accessed from function, but are not parameters:
function displayInfo()
{
## bad design
global $count, $info;
...
Or pass your array as parameter:
function displayInfo($info)
{
## this is local variable accessable only inside function
$count = count($info['level']);
...
}
The call it
<?php
## don't forget to pass array as parameter
displayInfo($info);
?>
You can either move your $count inside the function, or pass it to the function. Also, your $info array has to be passed into the function as well, or made a global. Here is the function prototype with count and info being passed into the function.
function displayInfo($count, $info)
{
for ($i=0; $i<$count; $i++)
{
// Do stuff
}
}
<?php
$count = count($info['level']);
displayInfo($count, $info);
?>
Indeed, there were no syntax errors, but there were other errors, as was pointed out in other reactions. I highly recommend configuring PHP to show all errors when writing new code. This way you would've seen a notice about $info and $count not being defined inside your function.
You can turn errors on in a couple of ways.
Configure your server to do it.
Turn them on by using an .htaccess file
Use the following PHP code in the very beginning of your script.
Example:
error_reporting(E_ALL | E_NOTICE); //turn on all errors
ini_set("display_errors","On"); //activate display_error

Categories