I am passing an array to a function and expecting the function to store values in it. Here's my code
The Function -
function GetDetailsById ($iStudentId, $aDetailsId)
{
/* SQL */
while ($row = mysql_fetch_array($result))
{
array_push($aDetailsId, $row[0]);
}
}
Usage -
$aDetailsId = array();
$oDetailsTable->GetDetailsById("1", $aDetailsId)
When I try to do
print_r($aDetailsId)
the array shows nothing. Am I doing it the right way?
Your array needs to be passed by reference to the function ; which means the function should be defined this way :
function GetDetailsById ($iStudentId, & $aDetailsId)
{
// ...
}
For more informations, see Making arguments be passed by reference
Or you could have your function return its result -- which might be better idea (looking at the code that calls the function, you immediately know what it does) :
function GetDetailsById ($iStudentId)
{
$result = array();
// TODO here, fill $result with your data
return $result;
}
And call the function :
$aDetailsId = $oDetailsTable->GetDetailsById("1");
That's because parameters are passed by value by default, meaning only the value of the variable is passed into the function, not the variable itself. Whatever you do to the value inside the function does not affect the original outside the function.
Two options:
return the modified value from the function.
Pass the parameter by reference:
function GetDetailsById ($iStudentId, &$aDetailsId) ...
first count/check your resutl is contain any resultset. and try using '&' in parameter of array
function GetDetailsById ($iStudentId, &$aDetailsId)
Please change function declaration to,
function GetDetailsById ($iStudentId, &$aDetailsId)
There is one more mistake in array_push call. Change it to,
array_push($aDetailsId, $row[0]);
Related
I have a function which converts a one-indexed 2d array to a 1d array.
Example:
Given array:
array(0 => array("name"=>"Roberts", "email"=>"email#email.com"));
Returned array:
array("name"=>"Roberts", "email"=>"email#email.com");
the function is like this:
function to_1d_array($array)
{
return $array[0];
}
But I want the function to change the passed variable directly returning anything. Should I user referencing or what?
Yes, change to:
function to_1d_array(&$array)
{
$array=$array[0];
}
You should be able to use pass-by-reference, like this:
function to_1d_array(&$array)
{
$array = $array[0];
}
Notice the ampersand (&) just before the $array parameter.
The PHP documentation on this topic has more information if you need it.
I'm curious if I can assign a variable the value of a specific array index value returned by a function in PHP on one line.
Right now I have a function that returns an associative array and I do what I want in two lines.
$var = myFunction($param1, $param2);
$var = $var['specificIndex'];
without adding a parameter that determines what the return type is, is there a way to do this in one line?
In PHP 5.4, you can do this: $var = myFunction(param1, param2)['specificIndex'];.
Another option is to know the order of the array, and use list(). Note that list only works with numeric arrays.
For example:
function myFunction($a, $b){
// CODE
return array(12, 16);
}
list(,$b) = myFunction(1,2); // $b is now 16
You could add an additional optional parameter and, if set, would return that value. See the following code:
function myFunction($param1, $param2, $returnVal = "")
{
$arr = array();
// your code here
if ($returnVal)
{
return $arr[$returnval];
}
else
{
return $arr;
}
}
I am familiar with scope but have not used it much. I know how to change a variable's value inside of a function if I know what the variable name is by using GLOBAL $variableName in the function.
I'm writing a method that is passed 2 arguments. The first will accept an array that contains strings and the second will hold settings to do such as md5 for encrypting and trim to trim spaces.
Is there a way I can change the first argument's value inside the function? or do you know of a better method to accomplish this?
function _Edit($string, $rules)
{
#check if array
if(is_array($rules)!=TRUE)
{array_push($GLOBALS[debug], '<span class="error">_Edits second arguement must be an array</span>');}
if(is_array($string)!=TRUE)
{array_push($GLOBALS[debug], '<span class="error">_Edits first arguement must be an array</span>');}else
{
#loop through the strings
foreach ($string as $sk=>$sv)
{
#make changes based on rules
/* order of rules is important.
the changes will be made in the order the rules are sent */
foreach ($rules as $rv)
{
switch ($rv)
{
case 'md5':
//$string[$sk] = md5($sv);
//GLOBALS[$string][$sk] = md5($sv);
break;
}
}
}
}
}
If I understand right, you want to change the value of the first argument outside of the function from inside the function? for this you will have to pass by reference, or you can just return the updated array and overwrite the original value.
http://php.net/manual/en/language.references.pass.php
Why don't you return the array you eventually modified in your function?
So...
$my_array = _Edit($my_array, $rules);
And in your function you do:
function _Edit($string, $rules) {
... your code ...
... modify $string ...
return $string;
}
The main function of the example class uses the reusableFunction twice with different data and attempts to send that data to a different instance variable ($this->result1container and $this->result2container) in each case, but the data doesn't get into the instance variables.
I could get it to work by making reusableFunction into two different functions, one with array_push($this->result1container, $resultdata) and the other with array_push($this->result2container, $resultdata), but I am trying to find a solution that doesn't require me to duplicate the code.
My solution was to try to pass the name of the result container into the function, but no go. Does somebody know a way I could get this to work?
Example Code:
Class Example {
private $result1container = array();
private $result2container = array();
function __construct() {
;
}
function main($data1, $data2) {
$this->reusableFunction($data1, $this->result1container);
$this->reusableFunction($data2, $this->result2container);
}
function reusableFunction($data, $resultcontainer) {
$resultdata = $data + 17;
// PROBLEM HERE - $resultcontainer is apparently not equal to
// $this->result1container or $this->result2container when I
// try to pass them in through the parameter.
array_push($resultcontainer, $resultdata);
}
function getResults() {
return array(
"Container 1" => $this->result1container,
"Container 2" => $this->result2container);
}
}
(If this is a duplicate of a question, I apologize and will happily learn the answer from that question if somebody would be kind enough to point me there. My research didn't turn up any answers, but this might just be because I didn't know the right question to be searching for)
It looks to me like you want to be passing by reference:
function reusableFunction($data, &$resultcontainer) {
...
If you don't pass by reference with the & then you are just making a local copy of the variable inside reuseableFunction .
You are changing the copy, not the original. Alias the original Array by referenceDocs:
function reusableFunction($data, &$resultcontainer) {
# ^
And that should do the job. Alternatively, return the changed Array and assign it to the object member it belongs to (as for re-useability and to keep things apart if the real functionality is doing merely the push only).
Additionally
array_push($resultcontainer, $resultdata);
can be written as
$resultcontainer[] = $resultdata;
But that's just really FYI.
You may pass the attributes name as a String to the method like this:
function reusableFunction($data, $resultcontainer) {
$resultdata = $data + 17;
array_push($this->{$resultcontainer}, $resultdata);
}
//..somewhere else..
$this->reusableFunction($data, 'result2Container')
Some php experts wrote some texts about "why you shouldn't use byReference in php".
Another solution would be to define the containers as an array. Then you can pass an "key" to the method that is used to store the result in the array. Like this:
private $results = array();
function reusableFunction($data, $resIdx) {
$resultdata = $data + 17;
array_push($this->$results[$resIdx], $resultdata);
}
//..somewhere else..
$this->reusableFunction($data, 'result2Container');
//..or pass a number as index..
$this->reusableFunction($data, 1);
By default a PHP function uses $_GET variables. Sometimes this function should be called in an situation where $_GET is not set. In this case I will define the needed variables as parameter like: actionOne(234)
To get an abstract code I tried something like this:
function actionOne($id=$_GET["ID"])
which results in an error:
Parse error: syntax error, unexpected T_VARIABLE
Is it impossible to define an default parameter by using an variable?
Edit
The actionOne is called "directly" from an URL using the framework Yii. By handling the $_GET variables outside this function, I had to do this on an central component (even it is a simple, insignificant function) or I have to change the framework, what I don't like to do.
An other way to do this could be an dummy function (something like an pre-function), which is called by the URL. This "dummy" function handles the variable-issue and calls the actionOne($id).
No, this isn't possible, as stated on the Function arguments manual page:
The default value must be a constant
expression, not (for example) a
variable, a class member or a function
call.
Instead you could either simply pass in null as the default and update this within your function...
function actionOne($id=null) {
$id = isset($id) ? $id : $_GET['ID'];
....
}
...or (better still), simply provide $_GET['ID'] as the argument value when you don't have a specific ID to pass in. (i.e.: Handle this outside the function.)
function actionOne( $id=null ) {
if ($id === null) $id = $_GET['ID'];
}
But, i would probably do this outside of the function:
// This line would change, its just a for instance
$id = $id ? $id : $_GET['id'];
actionOne( $id );
You should get that id before you call the function. Checking for the existence of the parameter breaks encapsulation. You should do something like that:
if (isset($_GET["ID"])
{
$id = $_GET["ID"];
}
else
{
//$id = something else
}
function doSomethingWithID($id)
{
//do something
}
You could use constant variable
define('ID',$_GET["ID"]);
function($id = _ID_){
//code
}
Yes it is impossible.
The default has to be a static variable:
function actionOne( $id='something') {
//code
}
Easy peanuts! (Might contain minor mistakes, errors or typos!)
You need a helper function, which will call you main function recursively, but having NULL as default:
Wrong: function actionOne($id=$_GET["ID"])
Right:
function actionOne($id) {...}
function actionOnewithID($id=NULL) {
if (NULL==$id){actionOne($_GET["ID"]);}
else {actionOne($id);
}
And if you need to return a value:
function actionOne($id) {...}
function actionOnewithID($id=NULL) {
if (NULL==$id){return(actionOne($_GET["ID"]));}
else {return(actionOne($id));
}
I hope this helps!
shortest way is:
function actionOne($id = null)
{
$id = $id ?? $_GET["ID"];
...
}