Jump to content

How can I break up a large foreach() ?


monkeypaw201

Recommended Posts

Alright, so i have the code below, and i've run it up to (and including) 3 Characters, but after that it wants over 256MB or Memory (hosting provider won't allocate more than that). Is there any way to break it up into smaller chunks?

[code<?php
$chars = array("A","a","B","b","C","c","D","d","E","e","F","f","G","g","H","h","I","i","J","j","K","k","L","l","M","m","N","n","O","o","P","p","Q","q","R","r","S","s","T","t","U","u","V","v","W","w","X","x","Y","y","Z","z"," ","`","~","1","!","2","@","3","#","4","$","5","%","6","^","7","&","8","*","9","(","0",")","-","_","=","+","\"","|","}","{","]","[",";",":","?","/",".",">","<");

function comb($a, $len){
   if ($len > count($a))return 'error';
   $out = array();
   if ($len==1) {
      foreach ($a as $v) $out[] = array($v);
      return $out;
   }
   $len--;
   while (count($a) > $len) {
      $b = array_shift($a);
      $c = comb($a, $len);
      foreach ($c as $v){
         array_unshift($v, $b);
         $out[] = $v;
      }
   }
   return $out;
}
$test = $chars;
$a = comb($test,$_GET['number']);
$count = 0;
foreach($a as $arr)
{
//print_r($arr);
$string = "";
$count++;

foreach($arr as $outrr)
{
	$string .= $outrr;
	//echo "<br>";
	//echo "-";
}
//echo $string;
//echo "-";
//echo "<br>";
//echo "<hr>";

mysql_query("INSERT INTO `sha1` (`string`) VALUES ('$string')");
}
echo $count;
?>

Link to comment
https://forums.phpfreaks.com/topic/150148-how-can-i-break-up-a-large-foreach/
Share on other sites

try

<?php
$chars = array("A","a","B","b","C","c","D","d","E","e","F","f","G","g","H","h","I","i","J","j","K","k","L","l","M","m","N","n","O","o","P","p","Q","q","R","r","S","s","T","t","U","u","V","v","W","w","X","x","Y","y","Z","z"," ","`","~","1","!","2","@","3","#","4","$","5","%","6","^","7","&","8","*","9","(","0",")","-","_","=","+","\"","|","}","{","]","[",";",":","?","/",".",">","<");
$total_number = 1;
$char_num = count($chars);
$len = $_GET['number'];
//$len =2;
for ($i=0; $i<$len;$i++) $total_number *= $char_num;
for ($i=0; $i<$total_number; $i++){
$a = $i;
$out = '';
for ($j=0;$j<$len;$j++){
	$out = $chars[$a % $char_num].$out;
	$a = (int) ($a/$char_num);
}
//	echo $out,"\n";
mysql_query("INSERT INTO `sha1` (`string`) VALUES ('$out')");
}
?>

think about time

for $len=2 time is in seconds

if $len=3 time is in minutes

$len=4 => hours

for $len=5 times is in days

for $len=6 times is in years etc.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.