Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop every 3 element in a PHP array? [duplicate]

Tags:

php

I have following PHP array:

 $array = array( 'uname', '=', 'lizabd', 'pass',  '=', '225555')

now I want to loop every 3 element like this way

 uname = lizabd
 pass  =  225555

How can I do this?

I know I can slice it using this for the first element:

 $slice = array_slice($array, 3);

But how can I do this using Loop ?

like image 821
Alex Avatar asked Mar 13 '18 07:03

Alex


1 Answers

You need to use array_chunk()

$array = array_chunk($array,3);

foreach($array as $arr){
  echo implode(' ',$arr);
  echo PHP_EOL; //for new line, you can also use echo '<br>';
}

Output:- https://eval.in/970842

Reference:- implode()

like image 165
Anant Kumar Singh Avatar answered Nov 15 '22 00:11

Anant Kumar Singh