3

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)
      {
      }
   }
8
  • what's your question exactly? Commented Nov 18, 2012 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. Commented Nov 18, 2012 at 4:12
  • assuming $varr is your array, then your foreach is backwards. syntax is foreach($array as $key => $value). Commented Nov 18, 2012 at 4:13
  • @Stegrex I have updated my question with the array Commented Nov 18, 2012 at 4:18
  • @BrianGlaz How can I achieve my goal Commented Nov 18, 2012 at 4:18

2 Answers 2

2

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.

0

try this:

foreach($var[0] as $varr)
{
  echo $varr->listingid;
}
2
  • From your code $varr would be an integer, not an object Commented Nov 18, 2012 at 4:34
  • what if property listingid does not exists? what if $var is not an object? Commented Nov 18, 2012 at 4:51

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.