0

I am trying to loop over the keys of an array and return the value when that key matches with a variable. But what I am doing just doesn't seem to make much sense.

public function check($variable)
{
    $result = 0;

    $amount = array(
        3 => 10,
        4 => 20,
        5 => 50
        );

    foreach ($amount as $a) {
        if ($a == $variable) {
            $result = $a[$amount];
        }
    }

    return $result;
}

At this point I am not even sure anymore if what I am doing is right :p

Anyone who could help me out?

Many thanks in advance!

3
  • What is your expected output. Can you please post that too Commented Nov 18, 2016 at 9:22
  • hmmm.... I'm betting it should be: $result = $a... but its unclear what you want.... Commented Nov 18, 2016 at 9:22
  • You use of keys and values is very confusing: What is the input and matching output? Some examples would help. Commented Nov 18, 2016 at 9:24

4 Answers 4

2
public function check($variable)
{
    $result = 0;

    $amount = array(
        3 => 10,
        4 => 20,
        5 => 50
    );

    if (isset($amount[$variable])) {
        $result = $amount[$variable];
    }

    return $result;
}
Sign up to request clarification or add additional context in comments.

Comments

0
public function check($variable)
{
    $result = 0;

    $amount = array(
        3 => 10,
        4 => 20,
        5 => 50
        );

    foreach ($amount as $k=>$v) {
        if ($k == $variable) {
            $result = $v;
        }
    }

    return $result;
}

Comments

0
function check($variable)
{
    $result = 0;
    $amount = array(
        3 => 10,
        4 => 20,
        5 => 50
        );


    foreach ($amount as $a) {
        if ($a == $variable) {
            $result = $a;
        }
    }

    return $result;
}

Basically the line assigning $a to $result wasn't in order. That was all that needed fixing. It now either returns 0 or the $variable if it's in the list. Frankly You were very close to the right code...

Comments

0

You don't need so much logic.. I think you don't need a function for that too, but here it is:

var_dump(check(4));

function check($variable)
{
    $amount = array(
        3 => 10,
        4 => 20,
        5 => 50
    );

    return isset($amount[$variable]) ? $amount[$variable] : 0;
}

As I can see this is a method inside a class.. it would be better to see all the methods from that class

2 Comments

How can I do this without a function?
It's a bit too much to show I want to do this check as part of an other rather big function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.