i want to display following array in output as 246,357 that is donot process first subarray and also the remaining subarray combination should be like $array[1][0].$array[2][0].$array[3][0]
,similarly combination should be $array[1][1].$array[2][1].$array[3][1]
$array=[
[0,1],
[2,3],
[4,5],
[6,7]
];
i have written follwing code but could not bypass first subarray so my output is 0246,1357
.plz help.
foreach($array as $n)
{
$a.=$n[0];
$b.=$n[1];
}
echo "$a".","."$b";
One way to skip the first element would be to use a flag variable $first
:
$first = true;
foreach ($array as $n) {
if ($first) {
$first = false;
} else {
$a .= $n[0];
$b .= $n[1];
}
}
Another way would be to remove the first element from the array, so it will be skipped over:
unset($array[0]);
Or check the key from within the foreach loop:
foreach ($array as $k => $n) {
if ($k > 0) {
$a .= $n[0];
$b .= $n[1];
}
}
Yet another way would be to use array_shift()
, which changes numeric keys in addition to removing the first element:
array_shift($array);
Finally, because your array contains only consecutive integer keys starting from 0, you could just use a normal for loop:
for ($i = 1; $i < count($array); $i++) {
$a .= $array[$i][0];
$b .= $array[$i][1];
}
Skip the first sub array by using a regular for
loop which starts at offset 1 instead of the foreach
loop.
for ($i = 1; $i <= count($array); $i++) {
$a.=$array[$i][0];
$b.=$array[$i][1];
}
Alternatives
Another code improvement suggestion
The line
echo "$a".","."$b";`
Can be written as
echo "{$a},{$b}";
Which I think is a lot more readable.
This will help you to skip the first array
foreach($array as $key => $n)
{
if($key>0)
{
$a.=$n[0];
$b.=$n[1];
}
}
You can use this:-
$flag = true;
foreach ($array as $n) {
if ($flag==false) {
$a .= $n[0];
$b .= $n[1];
} else {
$flag = false;
}
}
Check this anser without any loops :
$array=array(array(0,1),
array(2,3),
array(4,5),
array(6,7)
);
array_shift($array);
array_unshift($array, null);
$result = array_map("implode",call_user_func_array('array_map', $array));
echo "<pre>";
print_r($result);
Output :
Array
(
[0] => 246
[1] => 357
)