Accessing Individual Array Variables in PHP Function - php

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'];

Related

PHP: how to condition max(array_filter) & min(array_filter) if empty

I have created an array using compact:
$rank_month = compact('jan','feb','mar');
Like this and the data will be fetch using queries and due to that the data will sometimes will be empty and the data will be numbers.
And then I'm using the max(array_filter) and min(array_filter) to get the highest and lowest in the array but when the query is empty I get the
ERROR: max(): Array must contain at least one element
ERROR: Min(): Array must contain at least one element
is it possible to condition it like:
if(empty(max(array_filter('$rank_month')))){
$high = ""; }
else{
$high = max(array_filter('$rank_month'
}
or is their any way to fix this error? Even if the data is empty
Thanks.
You are passing array_filter a string when it actually wants an array. '$rank_month' is an 11-character string, it's not an array.
You want to make sure you pass the array to array_filter (as well as min and max).
You also want to be checking the length of the filtered array before calling min/max.
$filtered_month = array_filter($rank_month);
if(!empty($filtered_month)){
$high = max($filtered_month);
}
else{
$high = '';
}
simply what the error says: $rank_month is an empty array
use sizeof or count
if (sizeof($rank_month) > 1) {
$high = max($rank_month);
} else {
...
}
Or
if (count($rank_month) > 1) {
$high = max($rank_month);
else {
...
}
You need to check if the Array is empty, not if the max value is empty.
You also don't need to pass in array_filter, the array itself should work.
if(empty($rank_month)){
$high = "";
} else {
$high = max($rank_month);
}

composed variable after Object Operator in PHP

How can I build a composed variable while creating a variable in PHP?
(Sorry I'm not sure how to call the different elements)
This is what I'm trying to do:
$language = 'name_'.$this->session->userdata('site_lang');
for ($i=1;$i<=3;$i++) {
$data = $arraydata->$language_.$i; // problem is here
}
I would like $language_.$i to be equivalent to name_english_1, next loop name_english_2... The same way I built $language
If you want to use an expression in a computed property, you have to put the expression in braces. Also, you need to put the underscore in quotes.
$data = $arraydata->{$language."_".$i};
However, I suggest you redesign your data structure. Instead of having separate name_LANG_i properties, make a single name property whose value is a multi-dimensional array.
$lang = $this->session->userdata('site_lang');
for ($i=1;$i<=3;$i++) {
$data = $arraydata->name[$lang][$i];
// do something with $data
}
Whenever you find yourself using variable variables or variable properties, it's almost always a sign that you should be using an array instead.
First construct the field name and then use it for accessing the field value from the object $arraydata. So your code should be like this:
$language = 'name_'.$this->session->userdata('site_lang');
for ($i = 1; $i <= 3; $i++) {
$var = "{$language}_{$i}";
$data = $arraydata->$var;
// echo $data;
}

PHP - array change input from string into number when passing into class function

I am trying to pass array of 4 strings into function but inside that function it change third string into number 1, any clue why that happened and how to prevent that?
Here is some code I use for that:
Array I pass in:
$lista = array("user_info","county", $_POST['lokacja'], "ID_hrabstwa");
$ID_hrabstwa = VarGetter::getVar("IDHRABSTWA",$lista);
and function that take the array:
static public function getVar($varToGet,$data)
{
$DM = new DatabaseManager;
$column = array($data[0]);
$where = array($data[1]=>$data[2]);
$ID_hrabstwa = $DM->selectData($data[3], $column, $where);
return $ID_hrabstwa[0]['ID_hrabstwa'];
}
I also try to create a variable to hold that $_POST[] but no results either.
I will appropriate any kind of clue/explanation what am I doing wrong, why that happen.

PHP Functions - Returning arguments to mulitple variables

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']);

Use array from function directly, without assigning a variable first

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;
}
}

Categories