In PHP, using array slices makes it easier to code through the array_slice function.
P粉194541072
P粉194541072 2023-08-07 16:41:02
0
1
414
<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>
P粉194541072
P粉194541072

reply all(1)
P粉154798196

This is simpler:

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

I use thisTernary Operator.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template