I'm trying to perform two calculations in one function and return the values of both calculations to seperate variables. I think i have everything setup nearly correct but i'm getting an error message which i'll post after the code. I could easily write two functions to do what I want but i'd rather have it all in one function since the function is initiated by the click of one button.
function sg_gc1($gv_1, $g_1) {
$gv_1 = $gv_1 - 1;
Return $gv_1;
$g_1 = $g_1 + 20;
Return $g_1;
}
// This second part in my code is mostly irrelevant to my question but it helps paint the picture.
if (isset($_POST['Calculate']) && ($_SESSION['gv_1'] != 0) ) {
$_SESSION['gv_1'] = sg_gc1($_SESSION['gv_1']); // line 55
$_SESSION['g_1'] = sg_gc1($_SESSION['g_1']); // line 56
} // This statement assigns the new calculated values to my existing session variables and it worked just fine before i tried adding in the second argument
Warning: Missing argument 2 for sg_gc1(), called in F:PATH on line 55 and defined in F:PATH on line 6
Warning: Missing argument 2 for sg_gc1(), called in F:PATH on line 56 and defined in F:PATH on line 6
So the error is happening inside the function which leads me to believe the function is not set up properly for two arguments. It works just fine with 1 argument if i were to remove all the g_1 parameters.
Call function like this, because your function accepts two arguments and you are passing only one.
sg_gc1($_SESSION['gv_1'],$_SESSION['g_1']);
and in function you have to return like below. Your second return would never get executed.
function sg_gc1($gv_1, $g_1) {
$gv_1 = $gv_1 - 1;
$g_1 = $g_1 + 20;
return array($gv_1,$g_1);
}
Calling function part
if (isset($_POST['Calculate']) && ($_SESSION['gv_1'] != 0) ) {
list($_SESSION['gv_1'],$_SESSION['g_1']) = sg_gc1($_SESSION['gv_1'],$_SESSION['g_1']);
echo $_SESSION['gv_1']."--".$_SESSION['g_1'];//for checking purpose
}
You can't return two variables in a function. Return an array instead:
function sg_gc1($gv_1, $g_1) {
$gv_1 = $gv_1 - 1;
$g_1 = $g_1 + 20;
return array($gv_1, $g_1);
}
Now to retrieve the values, you can simply access the array indices:
$arr = sg_gc1($_SESSION['gv_1'], $_SESSION['g_1']);
$gv_1 = $arr[0];
$g_1 = $arr[1];
Or you could use the list construct to do it in one line:
list($gv_1, $g_1) = sg_gc1($_SESSION['gv_1'], $_SESSION['g_1']);
Related
This question already has answers here:
Accept function as parameter in PHP
(9 answers)
Closed 1 year ago.
I have two functions - the first function is complex and it takes around 15 seconds to load as it fetches data from third parties. The second one is a normal function. To illustrate this is what I have
<?php
class ComplexFunctions{
public function complexFunctionOne($x){
// do something
}
}
?>
<?php
function SimpleFunction($y, $z){
if($y){
// if $y is true use variable z
}else{
//if $y is false don't use variable z
}
return $a;
}
$cf = new ComplexFunctions();
$input_y = 'Y';
$input_y = 'Z';
$output = SimpleFunction($input_y, $cf->complexFunctionOne($input_y);
?>
I need to run the complex function $y only when the first variable $y is true. If it isn't I don't want to run it.
Unfortunately, regardless of whether $y is true or false - $cf->complexFunctionOne($input_y) is still loaded in any condition. This could take a lot of useless time for something that I do not want unless it's called specifically.
One solution could be to call $cf->complexFunctionOne($input_y) inside teh simple function, however, I have a hand full of complex functions e.g. complexFunctionTwo and I only want to use depending on the circumstance rather than have a Switch/Case statement.
well in order to pass a function, you can just:
$output = SimpleFunction($input_y, function() use ($input_y, $cf){
return $cf->complexFunctionOne($input_y);
};
so then you just need:
function SimpleFunction($y, $z){
if($y){
// if $y is true use variable z
$a = $z();
}else{
//if $y is false don't use variable z
$a = ...;
}
return $a;
}
In this way you will "lazy load" the result of $z
I'm attempting to edit a custom function and struggling to get the row value for a particular custom column ('rank_td') to compare against its other columns (rank_lw and rank_lm), all inside a HTML table.
Tried a fair few variations and can't get it going.
Any ideas?
function custom_value($cellValue, $dataColumnHeader, $rank_td_value) {
if($dataColumnHeader == "rank_lw" || $dataColumnHeader == 'rank_lm'){
$row['rank_td']->$cellValue = $rank_td_value;
if($rank_td_value == $cellValue){
$styleColor = 'color:blue;';
}else if($rank_td_value < $cellValue){
$styleColor = 'color:green;';
}else{
$styleColor = 'color:red;';
}
return $class_name.'<span style="'.$styleColor.'">'.$cellValue.'</span>';
}
return $cellValue; }
You are not calling the global variable $row which exists outside the scope of this function - hence my comment that it doesn't look like it belongs here. If you want to be able to access a variable from outside a function you need to either pass that variable in, or declare it using the global keyword. Here is a very basic example of this:
$row['some_value'] = "value1";
function scopeTest($var1) {
$row['some_value'] = $var1;//local variable $row created
}
function scopeTestTwo($var1) {
global $row;//variable outside the function
$row['some_value'] = $var1;
}
scopeTest("jam");
print_r($row);//Array ( [some_value] => value1 )
scopeTestTwo("jam");
print_r($row);//Array ( [some_value] => jam )
in your code you also have this
return $class_name.'<span....
but $classname is not defined so either it is redundant and you should remove it (because this will cause a php notice and anyway redundant code is, well, redundant) or it should be defined somewhere which means something has been missed out
I get a website as a cURL response, and I pass it to this function. Then I itterate through the string, doing some processing. It works, but I get this error:
Notice: Uninitialized string offset: 75817 in
/var/www/html/wp-content/plugins/crg-daily/lib/CragslistRawDumpProcessor.class.php
on line 7
Here is the code:
public function rollSausage($dump){
$anchorArray = array();
$dumpLength = strlen($dump);
$skipToLetter = 1;
while($skipToLetter < $dumpLength){
$skipToLetter++;
$letter = $dump[$skipToLetter];
...
}
}
Any ideas? I think it has something to do with the type of string being submitted. It is a raw cUrl response. I'm scraping a web page.
Increment your $skipToLetter after you use it (preferably at the end of the while loop). And you might also start at 0, not 1
$skipToLetter = 0;
while($skipToLetter < $dumpLength){
$letter = $dump[$skipToLetter];
...
$skipToLetter++;
}
}
Here's the reason: assume you have a string with length of 4. This means that the last index in the string is 3. Your index goes up to 3. It gets compared in the while loop (3<4)? and the answer is true. The code enters the while loop and increments the value of the index which will be greater than the last index of the string, thus causing the warning.
Updated your code...
public function rollSausage($dump){
$anchorArray = array();
$dumpLength = strlen($dump);
$skipToLetter = 1;
while($skipToLetter < $dumpLength){
$skipToLetter++;
if( siset( $dump[$skipToLetter]) )
$letter = $dump[$skipToLetter];
...
}
}
}
I have a function userNumber($number) where I want to return two variables. I know it's not possible to return more than one variable in PHP functions, so I created an array so I can access any index/value from the array when needed. The function tests if the user's input is between 100 & 200, and should output the cube and square root of the number.
I want to call the function in variables:
$calculationSquare = userNumber($number);
$calculationCube = userNumer($number);
But I do not see how I can access each value of the array in each variable(like the formatting of calling an index - array[]);
Here is the function that converts the number into square/cube and returns the value via array:
function userNumber($number) {
$square = "";
$cubed = "";
if(100 < $number && $number < 200) {
$sqaure = sqrt($number);
$cubed = $number * $number * $number;
return array($square, $cubed);
} // end if
else {
return false;
} // end else
} // end function userNumber
Again, here are the two variables that I'd like to populate with the return values (but don't know how to access he square or cube in the array to populate the variables accordingly):
$calculationSquare = userNumber($number);
$calculationCube = userNumber($number);
Any input on how to access the individual array values in the function would be appreciated, or resources on learning more about this.
In your current implementation you can do this in PHP >= 5.4.0:
$calculationSquare = userNumber($number)[0];
$calculationCube = userNumber($number)[1];
Or better, this would only call the function once:
$result = userNumber($number);
$calculationSquare = $result[0];
$calculationCube = $result[1];
Or maybe even better, use list() to assign array values to individual variables:
list($calculationSquare, $calculationCube) = userNumber($number);
The above approaches would also work with the following returned array, but it may be more descriptive:
return array('square' => $square, 'cube' => $cubed);
You can then use list() or:
$calculationSquare = $result['square'];
$calculationCube = $result['cube'];
I know you can use func_num_args to get the number of actual arguments passed in. Is there any way to get the number of formal parameters?
Example:
<?php
function optional($a, $b = null) {
echo func_num_args();
}
optional(1); // 1
optional(1, 1); // 2
optional(1, 1, 1); // 3
I want a way to get 2 in each of those calls to optional, without hard-coding it.
One way is with ReflectionFunction, e.g.:
function optional($a, $b = null) {
return (new ReflectionFunction(__FUNCTION__))->getNumberOfParameters();
}