Convert a piece of code into a php function
This is probably very easy to do, but for some reason I can't figure it out. Let's say I have code like this:
$elements = array('a', 'b', 'c', 'd');
$myValues = array(
'values' => array(
'a' => array(
'xx' => 3,
'yy' => ''
),
'b' => array(
'xx' => '',
'yy' => ''
),
'c' => array(
'xx' => 8.4,
'yy' => ''
),
'd' => array(
'xx' => 18.4,
'yy' => ''
)
)
);
foreach($elements as $elem)
{
if($myValues['values'][$elem]['xx'] != '')
{
if($myValues['values'][$elem]['xx'] < 6)
{
$myValues['values'][$elem]['yy'] = 'less than 6';
}
elseif($myValues['values'][$elem]['xx'] >= 6 && $myValues['values'][$elem]['xx'] < 15)
{
$myValues['values'][$elem]['yy'] = 'between 6 and 16';
}
else
{
$myValues['values'][$elem]['yy'] = 'greater than 15';
}
testFunc($myValues['values'][$elem]['xx']); // This is how I would call my function once I replace the code above
}
}
As you can see here, I am trying to change the value $myValues['values'][$elem]['yy']
based on some conditions. I want to do this to replace the section of if elseif else
codes with a function that does the same thing.
I've tried something like:
function testFunc($xx)
{
if($xx < 6)
{
$yy = 'less than 6';
}
elseif($xx >= 6 && $xx < 15)
{
$yy = 'between 6 and 16';
}
else
{
$yy = 'greater than 15';
}
return $yy;
}
But obviously it won't work because I am not changing the value $myValues['values'][$elem]['yy']
inside my function.
NOTE I really want to pass ONLY the value $myValues['values'][$elem]['xx']
inside my function and return the changed value $myValues['values'][$elem]['yy']
.
Can anyone help me with this?
Thank you in advance
source to share
EDIT : Rereading the question, I seem to have misunderstood it at first glance. There seems to be no need for links here. Wouldn't this work?
foreach ($elements as $element) {
$myValues['values'][$element]['yy'] = testFunc($myValues['values'][$element]['xx']);
}
Equally, if it $elements
always matches array_keys($myValues['values'])
, you can use links:
foreach ($myValues['values'] as &$value) {
$value['yy'] = testFunc($value['xx']);
}
source to share
testFunc () function
function testFunc(&$arr) {
foreach ($arr['values'] as &$values) {
if ($values['xx'] != '') {
if ($values['xx'] < 6)
$values['yy'] = 'less than 6';
elseif ($values['xx'] >= 6 && $values['xx'] <= 15)
$values['yy'] = 'between 6 and 15';
else
$values['yy'] = 'greater than 15';
}
}
}
Using:
testFunc($myValues);
print_r($myValues);
Output:
Array
(
[values] => Array
(
[a] => Array
(
[xx] => 3
[yy] => less than 6
)
[b] => Array
(
[xx] =>
[yy] =>
)
[c] => Array
(
[xx] => 8.4
[yy] => between 6 and 15
)
[d] => Array
(
[xx] => 18.4
[yy] => greater than 15
)
)
)
source to share