Take the tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am having an issue trying to work out how to use a function variable in a foreach loop so that I can do the following but its not working.

$var =

array(7) { [0]=> array(3) { ["listingId"]=> int(532712629) } [1]=> array(3) { ["listingId"]=> int(532712202) }

Works but not right:

foreach($var as $varr)
{
  var_dump($varr['id']);
{

Goal - Having the array variable as the foreach value

    foreach($var['id'] as $item)
    {
       if($item === $foo)
      {
      }
   }
share|improve this question
 
what's your question exactly? –  Brian Glaz Nov 18 '12 at 4:10
 
What does your $var array look like? What you're trying to do right now looks like you're parsing a multidimensional array. If you can show us what $var looks like and what you get when you do var_dump($varr['id']); then we will get a better sense of what to do. –  Stegrex Nov 18 '12 at 4:12
 
assuming $varr is your array, then your foreach is backwards. syntax is foreach($array as $key => $value). –  Marc B Nov 18 '12 at 4:13
 
@Stegrex I have updated my question with the array –  Jess McKenzie Nov 18 '12 at 4:18
 
@BrianGlaz How can I achieve my goal –  Jess McKenzie Nov 18 '12 at 4:18
show 3 more comments

closed as not a real question by nickb, Linger, Iznogood, Mac, Nimit Dudani Nov 18 '12 at 19:52

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.If this question can be reworded to fit the rules in the help center, please edit the question.

2 Answers

up vote 1 down vote accepted

This will loop through the array in your $var array:

foreach ($var as $k=> $v){
   foreach ($v as $k2=> $v2){
      echo $k2." ".$v2;
   }
}

in the for each, the $k will retunr the array key (numeric OR textual) as $v will return the value. You can output an array's content by using print_r($array); in most case.

share|improve this answer
add comment

try this:

foreach($var[0] as $varr)
{
  echo $varr->listingid;
}
share|improve this answer
 
From your code $varr would be an integer, not an object –  zerkms Nov 18 '12 at 4:34
 
what if property listingid does not exists? what if $var is not an object? –  djay Nov 18 '12 at 4:51
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.