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
This would make it simpler:
I use the Ternary Operator.
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 ofif
. The code is not that much shorter (5 instead of 7 lines), but it is much more readable than if/elseif/else constructs: