Garry Pettet
Garry Pettet

Reputation: 8288

Object of class stdClass could not be converted to string error when accessing array

I can't figure out how to get a certain value from an array that is returned to my by the Laravel PHP framework. I want to loop through this variable (called $user_ids) and get the value of each element, like so:

$sql = '(';
$limit = count($user_ids);      
  for ($i = 0; $i < $limit; $i++) {
    if ($i == $limit ) {
      $sql .= '"' . $user_ids[$i] . '")';
    } else {
      $sql .= '"' . $user_ids[$i] . '", ';          
    }
  }

I keep getting the error: Object of class stdClass could not be converted to string.

Here is the output of print_r($user_ids):

Array ( [0] => stdClass Object ( [id] => 5 ) [1] => stdClass Object ( [id] => 6 ) [2] => stdClass Object ( [id] => 4 ) [3] => stdClass Object ( [id] => 7 ) [4] => stdClass Object ( [id] => 3 ) )

And the output of var_dump($user_ids):

array(5) { [0]=> object(stdClass)#201 (1) { ["id"]=> string(1) "5" } [1]=> object(stdClass)#205 (1) { ["id"]=> string(1) "6" } [2]=> object(stdClass)#204 (1) { ["id"]=> string(1) "4" } [3]=> object(stdClass)#206 (1) { ["id"]=> string(1) "7" } [4]=> object(stdClass)#207 (1) { ["id"]=> string(1) "3" } }

I'm sure this is something very simple but I'm just new to PHP.

Thanks,

Upvotes: 1

Views: 1293

Answers (2)

aseferov
aseferov

Reputation: 6403

Simply glue array element with commas and wrap with braces:

// converting object with id param to array of ids
$user_ids = array_map(function($user) { 
  return (int)$user->id;
}, $user_ids); 

// joining user_ids with comma
$query = (sizeof($user_ids) > 0)? '('.implode(', ', $user_ids).')' : '';

Upvotes: 2

Garry Pettet
Garry Pettet

Reputation: 8288

Both asef and jetawe's answers helped so I've up voted them but I found two solutions. I prefer the first as it doesn't require the creation of a temporary variable ($tmp):

$sql = '(';
$counter = 0;
$limit = count($user_ids)-1;            
foreach ($user_ids as $item) {      
   if ($counter == $limit ) {
      $sql .= '"' . $item->id . '")';
   } else {
      $sql .= '"' . $item->id . '", ';          
   }
   $counter++;
}

but this also works:

$sql = '(';
$limit = count($user_ids)-1;        
for ($i = 0; $i <= $limit; $i++) {
   $tmp =  (array)$user_ids[$i];        
   if ($i == $limit ) {
      $sql .= '"' . $tmp['id'] . '")';
   } else {
      $sql .= '"' . $tmp['id'] . '", ';         
   }
}

Upvotes: 1

Related Questions