Ken Gordon
Ken Gordon

Reputation: 35

Value is definitely in the array, but it keeps returning false

In my ./includes/functions.php I have the following function

function ck_rank($rank)
{
    $strJsonFileContents = file_get_contents("./includes/globals.json");
    $status = json_decode($strJsonFileContents, true);
    $ranks = array();
    foreach ($status as $value) { 
        array_push($ranks, $value); 
    }
    if (in_array($rank, $ranks)) { 
        echo "true";
    } else { 
        echo "false" ; 
    }
}

In my main.php I'm using this to check the return of that function, and if true, display a , if false, it won't show the

if (ck_rank($rank)) { <td>........</td> }

Problem is, no matter what, the function always returns false.
I'm really new at json, and I'm sure there's a better way, but any help would be greatly appreciated! ty

Upvotes: 0

Views: 46

Answers (3)

Rohit Rasela
Rohit Rasela

Reputation: 445

You can use this function:

function ck_rank($rank)
{
    $strJsonFileContents = file_get_contents("./includes/globals.json");
    $status = json_decode($strJsonFileContents, true);

    if (empty($status[0]['ranks'])) {
        return false;
    }

    $rankData = $status[0]['ranks'];

    $rankData = explode(',', $rankData);

    $ranks = array();

    foreach ($rankData as $value) {
        array_push($ranks, strtolower(trim($value)));
    }
    if (in_array(strtolower(trim($rank)), $ranks)) {
        echo "true";
    } else {
        echo "false";
    }
}

Upvotes: 0

Nigel Ren
Nigel Ren

Reputation: 57121

The problem is that your not returning anything, you are just echoing the value true or false...

    if ( in_array($rank, $ranks)) { echo "true" ;}
            else { echo "false" ; }

Should be

    if ( in_array($rank, $ranks)) { 
        return true;
    }
    else { 
        return false; 
    }

Or you could simplify it to...

return in_array($rank, $ranks);

Upvotes: 1

maxpovver
maxpovver

Reputation: 1600

Your rank variable

[ { "ranks":"Director,Asst. Director,Captain,Lieutenant,Chief,Deputy Chief,Dep. Chief" } ]

is decoded as one string

"Director,Asst. Director,Captain,Lieutenant,Chief,Deputy Chief,Dep. Chief"

So you should first split it by comma. For example you can do it like this:

function ck_rank($rank)
    {
            $strJsonFileContents = file_get_contents("./includes/globals.json");
            // for your json [ { "ranks":"Director,Asst. Director,Captain,Lieutenant,Chief,Deputy Chief,Dep. Chief" } ]
            // $ranks variable will contain array:
            // [["ranks" => "Director,Asst. Director,Captain,Lieutenant,Chief,Deputy Chief,Dep. Chief"]] 
            $status = json_decode($strJsonFileContents, true);
            $ranks = explode(",", $status[0]['ranks']); 
            return in_array($rank, $ranks);
    }

Note that we add [0] because in your json it is an object in array with field ranks

Upvotes: 2

Related Questions