Problem with Array (expects parameter 2 to be array)

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Cheyens
    New Member
    • Aug 2013
    • 3

    Problem with Array (expects parameter 2 to be array)

    Hi,

    This works as long one or both Checkboxes are checked:

    Code:
    <?php if( in_array( 'Red', get_field('materiale') ) ) {echo '<a href="' . get_field('download') . '" target="_blank" class="readmore">Red →</a>';}?> <?php if( in_array( 'Blue', get_field('materiale') ) ) {echo '<a href="' . get_field('link') . '" target="_blank" class="readmore" >Blue →</a>';}?>
    But if "NONE" are checked I get this error:
    Warning: in_array() expects parameter 2 to be array, string given in

    How do I write this up properly?

    Thanks
    Last edited by Rabbit; Aug 11 '13, 07:22 PM. Reason: Please use code tags when posting code.
  • Cheyens
    New Member
    • Aug 2013
    • 3

    #2
    Maybe this needs further explanation:

    I'm using Advanced Custom Fields Plugin with WordPress and this:

    /*
    * Conditional statement (Checkbox rvalue is an array)
    */

    Code:
    if( in_array( 'red', get_field('field_name') ) )
    {
        //...
    }
    But how do I make two if( in_array without getting the "Problem with Array (expects parameter 2 to be array) error if none of the two checkboxes where ticked? How can it be "empty" without creating an error.

    Sorry...

    Comment

    • divideby0
      New Member
      • May 2012
      • 131

      #3
      It *looks* like get_field can return an array or a string depending on the field type. You might try short circuiting your if

      Code:
      $ret = get_field('field_name');
      
      if(is_array($ret) && in_array('red', $ret))
         // if path taken
      else
         // else path taken

      Comment

      • Cheyens
        New Member
        • Aug 2013
        • 3

        #4
        Hi,

        I've managed to solve it like this:

        Code:
        <?php 
        if( get_field('materiale') )
        {
        	if( in_array( 'Red', get_field('materiale') ) )
        	{
        		echo '<a href="' . get_field('download') . '" target="_blank" class="readmore">Red →</a>';
        	}
        }
        ?>

        Comment

        Working...