in_array() expects parameter 2 to be array, string

2019-08-05 20:39发布

I'm using Classipress theme for wordpress, and I'm trying to sticky my featured ads on the on in categories .

I found a code that is return this error:

Warning: in_array() expects parameter 2 to be array, string given in loop-ad_listing.php on line 26

To use the sticky on top code, I had to edit two pages and insert two codes and I'll post the error part:

First: loop-ad_listing.php

Code1:

global $postisfeatured;
global $featurePostArray;

if ($postisfeatured == "1") 
    array_push($featurePostArray, $post->ID);

if (in_array($post, "ID", $featurePostArray) && $postisfeatured != "1") 
    echo '<div class="hide">';

Code2:

if ($postisfeatured != "1") {
    appthemes_after_endwhile();
    $postisfeatured = "";
}

That line: if (in_array($post,"ID",$featurePostArray) && $postisfeatured != "1") { is the error.

4条回答
何必那么认真
2楼-- · 2019-08-05 20:48

the signature for in_array looks like:

  in_array($needle, $haystack, $strict = FALSE);

where:

needle is the string,int,resource etc which you're searching for.

haystack is the array in which you're searching

strict (optional) If (or not) the matched item should be identical (===)

查看更多
Deceive 欺骗
3楼-- · 2019-08-05 20:53

You aren't using the in_array function as it should be used.

In the second parameter you've placed a string (i.e "ID"), it's wrong; you should place the array that you wish to search in, at that spot.

The outcome should be something like this:

$valueToSearch = "a";
$arrayToSearch = array("a", "b", "c");
echo in_array($valueToSearch, $arrayToSearch);

Please refer to the documentation

查看更多
Animai°情兽
4楼-- · 2019-08-05 21:05

I think I solved this problem. I've got similiar situation in my form field select multiple which automatically creates not simple variable but array type variable(PHP weak var types). So when I declared the value at first in my code:

  1. $lang='';
  2. then $lang=$_POST['lang'];
  3. <select id="lang" name="lang[]" multiple size="3"> <option value="en"<?php if(in_array('en',$lang)) echo ' selected';?>>English</option> <option value="fr"<?php if(in_array('fr',$lang)) echo ' selected';?>>French</option> <option value="pl"<?php if(in_array('pl',$lang)) echo ' selected';?>>Polish</option> </select><br>
  4. and then I tried to run script and select none of the option I got known error "in_array() expects parameter 2..."
  5. solution is to set(in point 1.) to empty array $lang=array();
查看更多
霸刀☆藐视天下
5楼-- · 2019-08-05 21:06

You used "ID" as a second parameter which is a string. Try the following:

if ( is_array($featurePostArray) && in_array($post->ID, $featurePostArray) ) {
    //some action
}
查看更多
登录 后发表回答