skip to Main Content

I pull a row out of the database and I want to access it via a dynamic var

$prop = "theProp";

$test0 = $row["theProp"]; // Works fine
$test1 = $row->{$prop}; // Doesn't work
$test2 = $row->$prop; // Doesn't work

I’ve looked all over the place, obviously doing something stupid, can someone enlighten me please.

3

Answers


  1. You are so near, just replace "theProp" in $row["theProp"] with $prop.

    So this should work:

    $prop = "theProp";
    
    $test3 = $row[$prop];
    

    In your case, $row is an array, not an object, that’s why $row->$prop doesn’t work.

    Login or Signup to reply.
  2. Just try casting the array as an object. The below works fine:

    $array['one'] = "number 1, ";
    $array['two'] = "number 2, ";
    
    $object = (object) $array;
    
    echo $object->one;
    echo $object->two;
    
    
    
    Output: number 1, number 2, 
    
    Login or Signup to reply.
  3. Alternatively you can use fetch_object()/mysqli_fetch_object() when you pull data from the database. Your $row is an array and not an object, which is why your code doesn’t work.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search