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?
>Solution :
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.