0

I am trying to return an array however I keep getting the error:

Notice: Undefined variable: arr

I'm not sure where I went wrong?

<?php
$result = 1;
function getAns($result){
    if($result == 1){
        $arr = array("1"=>"A","2"=>"B");
    }
    elseif($result == 2){
        $arr = array("1"=>"D","2"=>"E");
    }
    return $arr;
}
getAns($result);
print_r($arr);
?>
Zestyy99
  • 287
  • 2
  • 10

2 Answers2

0

You are not using the returned value:

$result = 1;
function getAns($result){
    if($result == 1){
        $arr = array("1"=>"A","2"=>"B");
    }
    elseif($result == 2){
        $arr = array("1"=>"D","2"=>"E");
    }
    return $arr;
}
$arr = getAns($result); // use returned value : add '$arr ='
print_r($arr);

Outputs:

Array
(
    [1] => A
    [2] => B
)
Syscall
  • 19,327
  • 10
  • 37
  • 52
0
function getAns($i){
    $arr = array('', array('1'=>'A','2'=>'B'), array('1'=>'D','2'=>'E'));
    return $arr[$i];
}
shuai
  • 1
  • 1
  • again, please avoid code-only answers, always add some explanations. Also, please take a look at https://stackoverflow.com/help/how-to-answer – YakovL Mar 24 '18 at 20:51