Home > Software engineering >  if statement doesn't work after upgrading to PHP 8.1
if statement doesn't work after upgrading to PHP 8.1

Time:08-12

I unfortunately need to upgrade to PHP 8.1 (from 7.4) and that brings some changes (and unfortunately error messages). I'm not a programmer, but always got along with customizations so far, as I could see connections and adapt codes well.

I am now concerned with the following current example-code:

$quantity = (array($somefield));

if ( $quantity < 2 ) {
    Show a word in singular
}

if ( $quantity > 1 ) {
    Show a word in plural
}

That worked fine with PHP 7.4, but no longer with PHP 8.1 - only "Show word in plural" is displayed, even if there is only 1 field of a field (ACF in Wordpress). What am I doing wrong here?

CodePudding user response:

From the PHP docs "Comparison with Various Types":

array vs anything: array is always greater

object vs anything: object is always greater

array > integer // true
array > integer // true
array > object // false
object > array // true

In your code, I think you should be counting the values before:

// But, this will always be 1. Because your putting "$somefield"
// inside "array()" creating a new array with just 1 value.
// $quantity = count(array($somefield));

// UPDATE: Check if $somefield exist
if(isset($somefield)){
    // If you only want the count of the values inside $somefield, it should be
    $quantity = count($somefield);
    
    if ( $quantity < 2 ) {
        // Show a word in singular
    }
    
    if ( $quantity > 1 ) {
        // Show a word in plural
    }
}

CodePudding user response:

You need to check whether the field is a repeating field, which you can do with have_rows(). If it is, you can use count() to get the number of rows.

$fields = have_rows('field_name') ? get_field('field_name') : [get_field('field_name')];
$quantity = count($fields);
if ($quantity == 0) {
    // do something
} elseif ($quantity == 1) {
    echo "The field is: . $fields[0] . "<br>";
} else {
    echo "The fields are: <br>";
    foreach ($fields as $field) {
        echo "$field<br>";
    }
}
  • Related