I am facing a weird problem. I am trying to create a generic passenger list that populates itself. It decides on gender, name and male / female. Also if a family member will be added. This list has a counter ($person
) that works with a for function. So the first person on the list is 1, the second is a 2, if the 3rd is a family member of the second, the $person
integer gets a . However, this $person
creates two out of three times a memory issue and the page won't be loaded; fatal memory error (Fatal error: Allowed memory size of 536870912 bytes exhausted (tried to allocate 266338360 bytes))
How can this be solved?
function insertPax($class, $pax, $nat) {
for($person = 1; ; $person ) {
$fam = 0;
$first = "";
$first2 = "";
$id = array_rand($_SESSION['LAST'. $nat],1);
$lastname = $_SESSION['LAST'. $nat][$id];
$gender = rand(0,1);
if($gender == 1) {
$md = array_rand($_SESSION['MALE'. $nat],1);
$first = $_SESSION['MALE'. $nat][$md];
$sec = rand(1,8); if($sec == 1) {
$m2 = array_rand($_SESSION['MALE'. $nat],1); $first2 = $_SESSION['MALE'. $nat][$m2];
}
$gend = "MALE"; $comp = "FEMALE"; $age = rand(18,80);
} else {
$fd = array_rand($_SESSION['FEMALE'. $nat],1);
$first = $_SESSION['FEMALE'. $nat][$fd];
$sec = rand(1,8); if($sec == 1) {
$f2 = array_rand($_SESSION['FEMALE'. $nat],1); $first2 = $_SESSION['FEMALE'. $nat][$f2];
}
$gend = "FEMALE"; $comp = "MALE"; $age = rand(17,80);
}
$fam = rand(1,4);
if($fam == 1) {
$ag2 = rand(17,80);
$cmp = array_rand($_SESSION[$comp . $nat],1);
$companion = $_SESSION[$comp . $nat][$cmp];
$manf .= "<br /><span style='color:yellow;'>". $person ." : ". $lastname .", ". $first ." ". $first2 ." ". $gend ." [". $age ."]";
# $person ; # <-- MEMORY ERROR
$manf .= "<br />". $person ." : ". $lastname .", ". $companion ." ". $comp ." [". $ag2 ."]</span>";
} else {
$manf .= "<br />". $person ." : ". $lastname .", ". $first ." ". $first2 ." ". $gend ." [". $age ."]";
}
if($person == $pax) break;
}
return $manf;
}
CodePudding user response:
You're incrementing $person
in the for loop and also possibly in the second if
condition... but you're using ==
in your break comparison, so you're introducing the possibility of incrementing right past the value of $pax
, missing your condition, and running an infinite loop. I'll wager you can just do this:
if ($person >= $pax) break;