I am currently learning php, and am struggling to write the results of a function to an array. After a google search it seems as the the function I have created has a bug in it that will create an array that is too large:
Fatal Error: Allowed Memory Size of 134217728 Bytes Exhausted (CodeIgniter + XML-RPC)
Like I said, I am currently learning PHP, and the resources for a custom written script are fairly limited, therefore I am asking if anybody would be kind enough to give me a push in the right direction as to where my code is buggy...
function multiples($number) {
echo "$number entered";
$arr = array();
for ($i = 1; $i = $number; $i++)
{
if($i % 3 == 0){
$arr[] = $i;
}
else if($i % 5 == 0){
$arr[] = $i;
}
else {}
}
}
this returns this when accessing the file through xampp, '$number' being the argument for the function...
'$number' entered
Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 36 bytes) in C:\xampp\htdocs\assessment\one.php on line 12
for ($i = 1; $i == $number; $i++) {
if($i % 3 == 0){
$arr[] = $i;
}
else if($i % 5 == 0){
$arr[] = $i;
}
else {}
}
Use == instead of =, since == is a conditional operator while = assigns a value.
Related
I am working on a random RPG Map generator that get's inserted into the database for later retrieval. Basically the user will enter some minor details on the form and specify how many tiles of each terrain they need to have on the map. Then the tiles are randomly inserted into the map and database. I insert the tiles into an Array and then shuffle the results. I do a loop through the array and loop through and X & Y grid to insert the terrain data. But everytime I do that, I get a memory error: Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 32 bytes) This is my code:
$gridarray = array();
for ($jungle1 = 0; $jungle1 <= $jungle -1; $jungle1++) {
array_push($gridarray,"jungle");
}
for ($swamp1 = 0; $swamp1 <= $swamp -1; $swamp1++) {
array_push($gridarray,"swamp");
}
for ($cave1 = 0; $cave1 <= $cave -1; $cave1++) {
array_push($gridarray,"cave");
}
for ($mountain1 = 0; $mountain1 <= $mountain -1; $mountain1++) {
array_push($gridarray,"mountain");
}
for ($ocean1 = 0; $ocean1 <= $ocean -1; $ocean1++) {
array_push($gridarray,"ocean");
}
for ($volcanic1 = 0; $volcanic1 <= $volcanic -1; $volcanic1++) {
array_push($gridarray,"volcanic");
}
for ($desert1 = 0; $desert1 <= $desert -1; $desert1++) {
array_push($gridarray,"desert");
}
for ($dirt1 = 0; $dirt1 <= $dirt -1; $dirt1++) {
array_push($gridarray,"dirt");
}
for ($forest1 = 0; $forest1 <= $forest -1; $forest++) {
array_push($gridarray,"dirt");
}
for ($arctic1 = 0; $arctic1 <= $arctic -1; $arctic++) {
array_push($gridarray,"arctic");
}
for ($grass1 = 0; $grass1 <= $grass -1; $grass++) {
array_push($gridarray,"grass");
}
echo '<table cellspacing="0" cellpadding="0" border="0">';
$gridsquare = $xsize * $ysize;
$grid = 0;
shuffle($gridarray);
for ($x = 1; $x <= $xsize; $x++) {
echo '<tr>';
for ($y = 1; $y <= $ysize; $y++) {
$terrain = $gridarray[$grid];
$terrain_img = 'http://www.sw-bfs.com/images/grids/' . $terrain . '.png';
$query2 = " INSERT INTO terrain ( ent_id, ent_type, grid_img, grid_type, grid_exit_e, grid_exit_w, grid_exit_s, grid_exit_n, grid_exit_u, grid_exit_d, x, y) VALUES ( '$loc_id', 'terrain', '$terrain_img', '$terrain','1', '1', '1', '1', '0', '0', '$x', '$y') ";
$result2 = mysql_query($query2) or die(mysql_error());
echo '<td><img src="' . $terrain_img . '" title="' . $terrain . '"/></td>';
$grid++;
}
echo '</tr>';
}
echo "</table>";
It is telling me that the error is occurring on the line that reads like this:
array_push($gridarray,"arctic");
}
Obviously I am doing something wrong or at least I am not writing the code efficiently enough. Forgive me, I am still learning. Can someone provide some better assistance? Thank you in advance.
Never mind. This:
for ($arctic1 = 0; $arctic1 <= $arctic -1; $arctic++) {
array_push($gridarray,"arctic");
Is missing a 1 in $arctic++. Should be like this:
for ($arctic1 = 0; $arctic1 <= $arctic -1; $arctic1++) {
array_push($gridarray,"arctic");
Now works perfectly. Feel free to use my snippet above to create random maps for the database.
I am making currently migration from one database to another, project is on laravel so I am creating laravel command for this. I have one table with about 700000 records. I have created function with LIMIT and transactions to optimize query but still getting out of memory error from PHP.
Here is my code:
ini_set('memory_limit', '750M'); // at beginning of file
$circuit_c = DB::connection('legacy')->select('SELECT COUNT(*) FROM tbl_info');
$count = (array) $circuit_c[0];
$counc = $count['COUNT(*)'];
$max = 1000;
$pages = ceil($counc / $max);
for ($i = 1; $i < ($pages + 1); $i++) {
$offset = (($i - 1) * $max);
$start = ($offset == 0 ? 0 : ($offset + 1));
$infos = DB::connection('legacy')->select('SELECT * from tbl_info LIMIT ' . $offset . ', ' . $max);
DB::connection('mysql')->transaction(function() use ($infos) {
foreach ($infos as $info) {
$validator = Validator::make($data = (array) $info, Info::$rules);
if ($validator->passes()) {
if ($info->record_type == 'C') {
$b_user_new = Info::create($data);
unset($b_user_new);
}
}
unset($info);
unset($validator);
}
});
unset($infos);
}
Error is this:
user#lenovo /var/www/info $ php artisan migratedata
PHP Fatal error: Allowed memory size of 786432000 bytes exhausted (tried to allocate 32 bytes) in /var/www/info/vendor/laravel/framework/src/Illuminate/Database/Grammar.php on line 75
Error is show after importing about 50000 records.
There is kind of a "memory leak" in here. You need to find out which of the variables is hogging all of this memory. Try this function to debug and see which variable keep on growing constantly
function sizeofvar($var) {
$start_memory = memory_get_usage();
$tmp = unserialize(serialize($var));
return memory_get_usage() - $start_memory;
}
Once you know what variable is taking all the memory then you can start implementíng appropriate measures.
Found the answer, laravel caches all queries, so just: DB::connection()->disableQueryLog();
$testCase="";
$strength="";
$i="";$j="";$sum=0;
$submit=$_POST['submit'];
if(!empty($submit))
{
$testCase=$_POST['TestCase'];
$strength=$_POST['strength'];
}
else
{
die("Please enter the Number of <strong>test case</strong><br/> and <strong> Strength of audience</strong>");
}
while($testCase>0)
{
for($i=1;$strength;$i=$i+1)
{
$user[$i]=$i+1;
}
//finding the total number of stickers
for($j=1;$j<$strength;$j=$j+1)
{
$sum=$sum+$user[$j];
}
}
echo "The total number of <strong>Stickers</strong> are = " . $sum;
Because you do this: while ($testCase > 0) { and do not decrase the $testCase ever. Also, it's better if you put your loops into your if condition.
And you do not need to create $strength variable. Try this:
$sum = 0;
if (!empty($_POST["submit"]) && !empty($_POST["testCase"]) && !empty($_POST["strength"])) {
$testCase = $_POST["testCase"];
while ($testCase > 0) {
for ($i = 1; $i < $_POST["strength"];$i++) {
$user[$i] = $i + 1;
}
for ($j = 1; $j < $_POST["strength"]; $j++) {
$sum = $sum + $user[$j];
}
//Here you need to decrase testcase
$testCase--;
}
} else {
die("Please enter the Number of <strong>test case</strong><br/> and <strong> Strength of audience</strong>");
}
echo "The total number of <strong>Stickers</strong> are = " . $sum;
NOTE: In PHP arrays are always started with 0, if you do not specify keys directly. Check your for loops for this.
This line:
for($i=1;$strength;$i=$i+1)
should probably be:
for($i=1;$i<$strength;$i=$i+1)
this is the Question i have in my homework.
Using PHP, implement a function that calculates recursively the factorial of a given number below 100.The function should return 0, in case the passed value exceeds 100
and here my answer
<?php
function factorial($number)
{
if ($number >= 100) {
return 0;
}
return $number * factorial($number - 1);
}
print factorial(11);
?>
but the problem when i run the code this i have Fatal error:
Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 65488 bytes) in C:\xampp\htdocs\PhpProject1\index.php on line 20
this is the line 20 return $number * factorial($number - 1);
i think the problem i have is infinite loop :(
and i can't end this loop
try this:
function factorial($number)
{
if ($number >= 100) {
return 0;
}
if($number<= 1){
return 1;
}
return $number * factorial($number - 1);
}
Try this way.
<?
function factorial($number)
{
if ($number >= 100) {
return 0;
}
elseif($number<= 1){
return 1;
}
else{/* do nothing */ return $number * factorial($number - 1); }
}
print factorial(11);
?>
What i am trying to do is style a text retrieven from sql. But when i try to preview it i get *Fatal error: Maximum execution time of 30 seconds exceeded on line 64 *. I tryed puting ini_set('max_execution_time', 300); but still same problem. here is the code:
<?php
ini_set('max_execution_time', 300);
$info="<h3>Τεχνικά Χαρακτηριστικά</h3>";
$sql_1 = mysql_query("SELECT * FROM info WHERE parent = '$id'")or trigger_error(mysql_error());
$counter = mysql_num_rows($sql_1);
if($counter > 0){
while ($row_1 = mysql_fetch_array($sql_1)){
$temp = $row_1['add_info'] ."</br>";
$temp = str_split($temp);
for($i=0; $i <= sizeof($temp); $i++){
if($temp[$i] == ":"){
break;
}
}
$temp_1="<strong>";
for($w=0; $w < sizeof($temp); $w++){
if($w < $i+1){
$temp_1 .= $temp[$w];
}else if($w = $i+1){
$temp_1 .="</strong>";
}else{//this is line 64
$temp_1 .= $temp[$w];
}
}
$info .= $temp_1 . "<br/>";
}
}
?>
You are probably entering an infinite loop with line }else if($w = $i+1){, change that to }else if($w == $i+1){ or }else if($w === $i+1){.