skip to Main Content

I have 2 arrays and I need to display the elements of each array depending on their total number

In total, 2 elements from each array should be displayed, but if one of the arrays has 1 element, then display 3 elements from the other

I did it this way

array1 = [1, 2, 3, 4];
array2 = [1, 2, 3, 4];

if (count($array2) >= 2) {
    $array1 = array_slice($array1 , 0, 2);
} else if (count($array2 ) === 1) {
    $array1 = array_slice($array1 , 0, 3);
}

if (count($array1) >= 2) {
    $array2 = array_slice($array2 , 0, 2);
} else if (count($array1 ) === 1) {
    $array2 = array_slice($array2 , 0, 3);
}

This is a working code, but the question is, is it possible to somehow simplify the counting of the number of elements, and what would it take not 4 lines in the code, but one or two?

2

Answers


  1. This would make it simpler:

    $array1 = array_slice($array1, 0, count($array2) > 1 ? 2 : 3);
    $array2 = array_slice($array2, 0, count($array1) > 1 ? 2 : 3);
    

    I use the Ternary Operator.

    Login or Signup to reply.
  2. This does not really answer the question (‘…less lines’).

    Btw, the code in the OP misses in both ‘ifs’ the case of an empty array. So the line count would increase to 7 for each ‘if…endif’.

    As of PHP 8 we can use match instead of if. The code is not that much shorter (5 instead of 7 lines), but it is much more readable than if/elseif/else constructs:

    $array1 = match ( count($array2) ) {
      0       => $array1,
      1       => array_slice($array1, 0, 3),
      default => array_slice($array1, 0, 2)
    };
    
    $array2 = match ( count($array1) ) {
      0       => $array2,
      1       => array_slice($array2, 0, 3),
      default => array_slice($array2, 0, 2)
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search