Can print_r($array) but not echo $array['value']

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
davidcroda
Forum Newbie
Posts: 9
Joined: Wed Nov 08, 2006 10:36 am

Can print_r($array) but not echo $array['value']

Post by davidcroda »

This error is blowing my mind. I am querying an SQL database and placing the result in an array. When I do a print_r of the array ($contest) I get this:

stdClass Object ( [id] => 1 [title] => title [description] => description [start_date] => 2009-08-30 [end_date] => 2009-08-31 )

yet when I do echo $contest['title'] (or any of the array key's) the script stops executing, no error message, no nothing.

I can provide more code if it is necessary. I am at my wits end. Thanks!
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Can print_r($array) but not echo $array['value']

Post by requinix »

$contest isn't an array.
stdClass Object
AlanG
Forum Contributor
Posts: 136
Joined: Wed Jun 10, 2009 1:03 am

Re: Can print_r($array) but not echo $array['value']

Post by AlanG »

You are returning it as an object as opposed to an array.

Try:

Code: Select all

<?php
    echo $contest->title; // As opposed to $contest['title'];
?>

Code: Select all

<?php
$query = "SELECT * FROM mytable WHERE id='1'";
$result = $mysqli->query($query); // $result now contains an object
$contest = $result->fetch_assoc(); // $contest now contains an associative array of all the fields in the selected row
?>
davidcroda
Forum Newbie
Posts: 9
Joined: Wed Nov 08, 2006 10:36 am

Re: Can print_r($array) but not echo $array['value']

Post by davidcroda »

You guys are amazing. I just looked in the error log and found

PHP Catchable fatal error: Object of class stdClass could not be converted to string

I wish I could have the past 2 hours back.

Feel free to delete or close this post. Thanks again!
Post Reply