In PHP, using array slices makes it easier to code through the array_slice function.
P粉194541072
2023-08-07 16:41:02
<p>I have two arrays and need to display the elements of each array based on their total number of elements. <br /><br />In this way, the elements of array 1 will be displayed in order of the total number of elements, and the elements of array 2 will only display 1 element. </p><p><br /></p>
<pre class="brush:php;toolbar:false;">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);
}</pre>
<p>This is valid code, but what's the problem? Is it possible to simplify counting the number of array elements and not require more than 4 lines of code? </p>
This is simpler:
I use thisTernary Operator.