Blog coding and discussion of coding about JavaScript, PHP, CGI, general web building etc.

Saturday, August 20, 2016

an better way to do this code

an better way to do this code


myarray[] = $my[$addintomtarray]    //52 elements    for ($k=0; $k <= 12; $k++){        echo  $myarray[$k].' ';    }    echo '
'; for ($k=13; $k < 26; $k++){ echo $myarray[$k].' '; } echo '
'; for ($k=26; $k < 39; $k++){ echo $myarray[$k].' '; } echo '
'; for ($k=39; $k <= 51; $k++){ echo $myarray[$k].' '; }

how to shorten this array code...all I am doing here is splitting an array of 52 elements into 4 chunck of 13 elements each. In addition I am adding formation with br and space

thanks

Answer by R Samuel Klatchko for an better way to do this code


Use the modulus operator (%) to know when you are at a multiple of 13:

for ($k=0; $k <= 51; $k++){        echo  $myarray[$k].' ';      if (($k > 0) && (($k % 13) === 0)) {          echo '
'; } }

Answer by Jan Kuboschek for an better way to do this code


Loop through all elements in one loop. Use a % comparison conditionally.

~Edit~ See Mr. Klatchko's code below.

Answer by Kerry Jones for an better way to do this code


You definitely don't need to do that many for

loops:

$myarray[] = $my[$addintomtarray];  //52 elements    $i = 1;  foreach( $myarray as $v ){      echo "$v ";        if( 0 == $i % 13 )          echo '
'; $i++; }

Answer by radicalmatt for an better way to do this code


A better way to do this might be to use the array_slice function.

From the docs:

array array_slice ( array $array , int $offset [, int $length [, bool $preserve_keys = false ]] )  

"array_slice() returns the sequence of elements from the array array as specified by the offset and length parameters."

Answer by strager for an better way to do this code


I came up with this this idiom just yesterday to prevent flooding by my web crawler.

$myarray[] = $my[$addintomtarray]      // ...    // NOTE: This modifies $myarray!  Make a copy of it first if you  // need to (e.g. by making this its own function and passing by-value).    while(($line = array_splice($myarray, 0, 13))) {      echo implode(' ', $line);        if(count($myarray) !== 0) {          echo '
'; } }

Answer by Rob Wilkerson for an better way to do this code


I've always preferred to use array_chunk(). Once I get the array distributed in its raw form, I can display it any way I want.

array_chunk( $myarray, 13 );  

Now you have a 4 element array, each element of which contains a 13 element array. A simple nested loop will allow you to iterate and display in whatever manner you choose.


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

Related Posts:

0 comments:

Post a Comment

Popular Posts

Fun Page

Powered by Blogger.