2

I need to use a key from an array for a check.

The array comes from a PDO query like this

function getProject($proj_id) {
    $database = new Database();
    $database->query( "SELECT * FROM projects WHERE proj_id = '$proj_id' LIMIT 1" );
    $project = $database->resultSet();
    return $project;
}

Then I print the array which works like it should.

$project = getProject(1);
print_r($project);

Array ( [0] => Array ( [proj_id] => 73 [proj_name] => Cake )

But when I try to print a specific key from the array like this:

print_r($project['proj_name'];

Nothing gets printed on the screen. Why not?

3 Answers 3

6

You have two arrays:

Array ( [0] => Array ( [proj_id] => 73 [proj_name] => Cake )
  ^--this one    ^--and this one      

You need to do:

print_r($project[0]['proj_name']);

Probably the ideal situation would actually be to change it here:

function getProject($proj_id) {
  $database = new Database();
  $database->query( "SELECT * FROM projects WHERE proj_id = '$proj_id' LIMIT 1" );
  $project = $database->resultSet();
  return $project[0]; //<---added the [0] this line 
}

since you know it will always return one

Sign up to request clarification or add additional context in comments.

2 Comments

But where does that second array come from?
Your resultSet() function (which is not standard) probably calls PDO's fetchAll(), which always returns a 2D array, even for single rows.
1

If you look carefully, you'll see that you have two arrays nested one inside the other. Try print_r($project[0]['proj_name'];

Comments

1

You're missing a close-paren ) at the end of your print_r call.

You're seeing nothing on the screen because this means the file cannot be parsed, and errors are being logged to a file rather than displayed on screen. See How do I get PHP errors to display? for how to fix that.

4 Comments

While technically correct, that seems like it's just a copy-paste error, and not the actual issue.
you are right, but even with the close-paren ')' it wouldn't do what he wanted to do.
It would explain the "Nothing gets printed on the screen." If the problem is simply that OP isn't passing the right value to print_r(), something would print.
i think it would only show a warning if you have them enabled. Otherwise it just stays blank. At least i tried it at writecodeonline and it shows nothing.

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.