convert portion of code into a function php

Posted by user765368 on Stack Overflow See other posts from Stack Overflow or by user765368
Published on 2012-03-29T22:11:22Z Indexed on 2012/03/29 23:29 UTC
Read the original article Hit count: 229

Filed under:
|

This is probably very easy to do but for some reason I can't seem to figure this 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 what I'm trying to do is to change the value of $myValues['values'][$elem]['yy'] based on some conditions. What I want to do is to replace the if elseif else section of codes by a function that performs the same action.

I 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 this won't work because I'm not changing the value of $myValues['values'][$elem]['yy'] inside my function.

NOTE I really want to pass ONLY the value of $myValues['values'][$elem]['xx'] inside my function and return the changed value of $myValues['values'][$elem]['yy'].

Can anybody help me with this?

Thanks in advance

© Stack Overflow or respective owner

Related posts about php

Related posts about php5