jmenezes
jmenezes

Reputation: 1926

Stuck with php function with boolean

In the following code, I'm trying to do as you'll see below.

<?php
$urlHead = 'a';

function heading($urlHead){
    switch($urlHead){
        case 'c':
        $tab = '1';
        break;

        case 'i':
        $tab = '2';
        break;

        case 'r':
        $tab = '3';
        break;

        case 'a':
        $tab = '4';
        break;

        default:
        return false;
    }
}


if (heading($urlHead)) {
    echo 'Success;
        echo $tab;
} else {
    echo 'Fail';

}
?>

It's got to return true, and also the$tab value from inside the function. But $tab = 1 = false. This whole thing has me in knots. Can you help?

Upvotes: 0

Views: 98

Answers (3)

ishenkoyv
ishenkoyv

Reputation: 673

You don't have return in case of 'a' in heading. Default return is null which interpreted as false Also you have $tab in method and outside of it in different scopes

Upvotes: 0

Lorenzo Aiello
Lorenzo Aiello

Reputation: 474

You aren't returning the $tab variable.

New Code

function heading($urlHead){
  switch($urlHead){
    case 'c':
    $tab = '1';
    break;

    case 'i':
    $tab = '2';
    break;

    case 'r':
    $tab = '3';
    break;

    case 'a':
    $tab = '4';
    break;

    default:
    return false;
  }
  return $tab;
}

Upvotes: 0

Andrew
Andrew

Reputation: 5340

See this, basically, you need to return the $tab;

<?php
$urlHead = 'a';

function heading($urlHead)
{
    switch ($urlHead)
    {
        case 'c' :
            $tab = '1';
            break;

        case 'i' :
            $tab = '2';
            break;

        case 'r' :
            $tab = '3';
            break;

        case 'a' :
            $tab = '4';
            break;

        default :
            return false;
    }

    //return $tab
    return $tab;
}

$tab = heading ( $urlHead );

if ($tab)
{
    echo 'Success';
    echo $tab;
}
else
{
    echo 'Fail';
}

Upvotes: 1

Related Questions