Reputation: 6697
I have an array that contains different number of items every time. And I need to put this condition on the way of it:
"if the number of items are less than 2, then print
nothihg
, if the number of items are between 2 and 4, then print the first two items, if there are 5 items, then print all items".
Noted that the max number of array's items is 5
.
$myarr = ["one", "two", "three"];
foreach($myarr as $item){
if( count($myarr) >= 2 && count($myarr) < 5 ){
echo $myarr[0].PHP_EOL;
echo $myarr[1];
} else if( count($myarr) == 5 ){
echo $myarr[0].PHP_EOL;
echo $myarr[1].PHP_EOL;
echo $myarr[2].PHP_EOL;
echo $myarr[3].PHP_EOL;
echo $myarr[4];
} else {
echo "nothing";
break;
}
}
As you can see, I've used echo $var[i]
statically. How can make it shorter and dynamical?
Upvotes: 1
Views: 88
Reputation: 171
$myarr = ["one", "two", "three", "four", "five"];
$output = '';
foreach($myarr as $k=>$item){
if( count($myarr) >= 2 && count($myarr) < 5 && $k<2){
$output .= $item.PHP_EOL;
} else if( count($myarr) == 5 ){
$output .= $item.PHP_EOL;
} else if(count($myarr) <2) {
$output .= "nothing";
break;
}
}
echo $output;
Upvotes: 0
Reputation: 13635
There's many ways to skin this cat. These are my two cents:
$array = ["one", "two", "three"];
$count = count($array);
$iterations = 0;
if ($count < 2) {
echo 'nothing';
} else {
$iterations = $count <= 4 ? 2 : $count;
}
for ($i = 0; $i < $iterations; $i++) {
echo $array[$i] . PHP_EOL;
}
Demo: https://3v4l.org/CWHuj
Note: This version was just for fun. Writing code like this in any other context should be illegal.
$array = ["one", "two", "three"];
$count = count($array);
if (!$iterations = $count < 2 ? 0 : ($count <= 4 ? 2 : $count)) echo "nothing";
for ($i = 0; $i < $iterations; $i++) echo $array[$i] . PHP_EOL;
Demo: https://3v4l.org/N1fnv
Upvotes: 4
Reputation: 43574
You can use the following solution:
<?php
$myarr = ["one", "two", "three"];
$items_count = count($myarr);
if ($items_count < 2) {
echo "nothing";
} elseif ($items_count >= 2 && $items_count <= 4) {
echo implode(PHP_EOL, array_slice($myarr, 0, 2));
} else {
echo implode(PHP_EOL, $myarr);
}
You don't need the foreach
loop in this case. A simple list of conditions using count
can do it.
Upvotes: 6