-1

I have a JSON array converted to a PHP associative array. I'm attempting to loop through this associative array, and where the key matches a value held in a separate array ($filter), I want to echo the key and value from my associative array.

$filter = array("test1", "test");

foreach ($central as $key => $value) {
   $key = str_replace("_", " ", $key); 
   if(in_array('$filter', $key)){
       echo "<ul>".ucwords($key).':' .' '. $value."</ul>";
    }
   else { 
       continue;
   }
}

So to recap, if the $key of my $central associative array is equal to a value in my $filter array I want to echo out the values. Else go to the next item in the loop. This code does not work however,

syntax error, unexpected '=>'

Liam Fell
  • 1,308
  • 3
  • 21
  • 39
  • 1
    Read the manual about [`in_array()`](http://php.net/manual/en/function.in-array.php) and see: http://stackoverflow.com/q/3446216/3933332 (+ Error is not reproducible: https://3v4l.org/B9XhX) – Rizier123 Dec 14 '15 at 16:42
  • It would also be useful to see an example of the `$central` array, as replacing `_` with a space may not generate a match to your `$filter` arrays content either – RiggsFolly Dec 14 '15 at 16:50

2 Answers2

0

Not sure if I understand you correctly, but I think you have the "needle" and "haystack" the wrong way round. Also there is no need for the else statement.

foreach ($central as $key => $value) {
   $key = str_replace("_", " ", $key); 
   if(in_array($key, $filter)){
     echo "<ul>".ucwords($key).':' .' '. $value."</ul>";
   }
}
Armon Bigham
  • 339
  • 2
  • 14
0

To use in_array function you had to insert the key you are looking for (needle) as first parameter and the array as second parameter.

See php documentation for further information.

Here is the code with the correct call to the in_array function.

foreach ($central as $key => $value) {
    $key = str_replace("_", " ", $key); 
    if(in_array($key, $filter)){
        echo "<ul>".ucwords($key).':' .' '. $value."</ul>";
    }
}

Note that continue statement is useless because is at the end of the for loop.

Lipsyor
  • 428
  • 1
  • 7
  • 20