casper
casper

Reputation: 461

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 36 bytes)

i have made a function will return N-th digit of sequence number, example :

1234567891011121314151617

My function is like this

 <?php
   function getLength($number) {
   $length = 0;
   if ($number == 0){
      $length = 1;
   } else {
      $length = (int) log10($number)+1;
   }
     return $length;
  }
 ?>

<?php
 function getDigitNumber($digit){
   $number = 10000000000;
   $data = array();
   for($i=1;$i<=$number;$i++){  
   if(getLength($i) > 1){
     $array = str_split($i,1);
    for($n=0;$n<=count($array)-1;$n++){
        array_push($data,$array[$n]);
    }   
}else{
    $data[$i] = $i;
}
  } 
return $data[$digit];
}
?>

When i executed that i've a problem like this error message "Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 36 bytes)". Maybe because i assign a large number in var $number

How can i fix that..or how can i make function that can handle these large number

thanks..

Upvotes: 1

Views: 2190

Answers (2)

tmuguet
tmuguet

Reputation: 1165

About the memory problem, it is indeed due to the large number:

$number = 10000000000;
$data = array();
for($i=1;$i<=$number;$i++){  
    if(getLength($i) > 1){
        $array = str_split($i,1);
        for($n=0;$n<=count($array)-1;$n++){
            array_push($data,$array[$n]);
        }
    } else{
        $data[$i] = $i;
    }
} 

Basically, it allocates an array ($data) of ~500,000,000,000 items, which is quite big...

Manipulating your number as a string (or as a character array) as suggested in the other answers/comments will be: easier, more readable, faster, less memory-consuming, ...

Upvotes: 2

Fabian Schmengler
Fabian Schmengler

Reputation: 24576

i have made a function will return N-th digit of sequence number, example :

1234567891011121314151617

The 5-th digit is 5
The 20-th digit is 1

Why not:

$number[5];
$number[20];

The number has to be a string anyways, so just access the character with array syntax.

Upvotes: 10

Related Questions