phparraysarray-key-exists

Undefined offset despite array_key_exists() check


When using the code below in a function ($floor & $lift are passed in but I've added them here for demonstration) I'm getting an Notice: Undefined offset: 20 on the last return statement.

The last return is the mean that's mean to be used in this example but why am I getting the Notice: Undefined offset: 20? If I'm not mistake (which I clearly am) the array_key_exists() function should be preventing this? I've also tried it with isset() with no success.

$floor = 20;
$lift = false;

$moving = array(
    "no_lift" => array(
        1 => 0,
        2 => 13,
        3 => 17,
        4 => 20
    ),
    "lift"    => array(
        1 => 0,
        2 => 10,
        3 => 10,
        4 => 20
    )
);

switch ( $lift ) {
    case true:
        return ( isset( $moving["lift"][ $floor ] ) ? $moving["lift"][ $floor ] : $moving["lift"][ end( $moving["lift"] ) ] );
        break;
    case false:
        return ( array_key_exists( $floor, $moving["no_lift"] ) ? $moving["no_lift"][ $floor ] : $moving["no_lift"][ end( $moving["no_lift"] ) ] );
        break;
}

Solution

  • end returns the last value from an array, so

    $moving["lift"][ end( $moving["lift"] ) ]
    

    and

    $moving["no_lift"][ end( $moving["no_lift"] ) ]
    

    will both be, in effect,

    $moving["no_lift"][ 20 ]
    

    If you are intending to look for something in the array and return the last item if it isn't found, you can use in_array if you're looking for a value

    if ($lift) {
        return in_array($floor, $moving['lift']) ? $floor : end($moving['lift']);
    } else {
        return in_array($floor, $moving['no_lift']) ? $floor : end($moving['no_lift']);
    }
    

    or isset if you're looking for a key.

    if ($lift) {
        return isset($floor, $moving['lift']) ? $moving['lift'][$floor] : end($moving['lift']);
    } else {
        return isset($floor, $moving['no_lift']) ? $moving['no_lift'][$floor] : end($moving['no_lift']);
    }
    

    You can use array_key_exists rather than isset if some of the values in the array may be null. (You can check the answers here for a bit more of a description about that.)