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?

Kevin Panko
  • 7,844
  • 19
  • 46
  • 58

3 Answers3

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

dave
  • 50,635
  • 4
  • 62
  • 77
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'];

Alex Grin
  • 7,761
  • 6
  • 28
  • 53
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.

Community
  • 1
  • 1
dimo414
  • 42,340
  • 17
  • 131
  • 218
  • 1
    While technically correct, that seems like it's just a copy-paste error, and not the actual issue. – dave Dec 23 '14 at 17:59
  • 1
    you are right, but even with the close-paren ')' it wouldn't do what he wanted to do. – Tiago Dec 23 '14 at 18:00
  • 1
    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. – dimo414 Dec 23 '14 at 18:00
  • 1
    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. – Tiago Dec 23 '14 at 18:04