Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Simplify array slicing with array_slice php

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading