Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 202
  • Last Modified:

PHP Objects

Greetings, I have a variable that is instantiated as a PHP Object

$stats

$stats has some key->values assigned to it

$stats->gender = "male";
$stats->age = 34;

if I want the gender I can:
<?PHP echo $stats->gender ?>

what if I want the fieldname, not fieldvalue...
ie.  I want "gender" to appear, not "male"...

Thanks.
0
Evan Cutler
Asked:
Evan Cutler
  • 3
  • 2
  • 2
  • +1
2 Solutions
 
sivagnanam chandrakanthCommented:
Use this

echo $key = key((array)$stats);
0
 
Evan CutlerAuthor Commented:
Thank you sivagnanum_c,

How do I differentiate one from another?
There's gender and age...
How do I pick one out?

Thanks
0
 
Vimal DMCommented:
Hi,

just use the below code to print the field name

<?PHP
      echo key($stats);
 ?>
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
Evan CutlerAuthor Commented:
Ok, the problem is in this scenario, I have two fields....
How do I tell one from the other with that snippet?

Thanks.
0
 
Vimal DMCommented:
This might the useful one for you,i think

foreach($stats as $key=>$value){
      echo $key.'::'.$value.'<br>';
}
0
 
sivagnanam chandrakanthCommented:
see example

<?php
$obj = (object)array("Test" => "bar","test2"=>"val2");

$array= get_object_vars($obj); 
foreach($array as $key=>$val){
echo $key;
}
//echo $key = key((array)$obj);
?>

Open in new window

0
 
Slick812Commented:
greetings   arcee123  , , what you have said so far does not give me enough information about what you are trying to do AND what the Variables you have to start with ?

If  you know the property Name (sometimes referred to as the KEY) you just echo out that
echo "This is the Age ".$stats->age;

However you can NOT have a variable like  $var   without the  ->  ($var->property) and get any info about a single Property name, because there is NO property specified with $var

you say "I have two fields....  How do I tell one from the other with that snippet"
can you show us the PHP code (variables) for the two fields ? It may make a difference in how to solve this.
0
 
Evan CutlerAuthor Commented:
Thanks guys...most appreciated.
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

  • 3
  • 2
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now