I'm currently hand coding my if else statement
if ($user_location[0] == $location){
$user_id = $page[0];
} else if ($user_location[1] == $location){
$user_id = $page[1];
} else if ($user_location[2] == $location){
$user_id = $page[2];
} else if ($user_location[3] == $location){
$user_id = $page[3];
} else if ($user_location[4] == $location){
$user_id = $page[4];
} else if ($user_location[5] == $location){
$user_id = $page[5];
} else if ($user_location[6] == $location){
$user_id = $page[6];
} else if ($user_location[7] == $location){
$user_id = $page[7];
} else if ($user_location[8] == $location){
$user_id = $page[8];
} else {
$user_id = $user_gen;
}
How do I make this if statement that auto increment the $user_location[]
and $page[]
instead of hand coding?
Try this:
I assume you are using PHP as per you tag your question in PHP
$flag = true;
foreach($user_location as $index=>$each){
if ($each == $location){
$flag = false;
$user_id = $page[$index];
}
}
if ($flag){
$user_id = $user_gen;
}
The easiest solution is probably to use foreach
:
$user_id = $user_gen;
foreach($user_location as $key => $ulocation) {
if ($ulocation == $location) {
$user_id = $page[$key];
break;
}
}
Can you try this ?
$user_id = $user_gen;
foreach($user_location as $key => $value){
if($value == $location){
$user_id = $page[$key];
$location_find = true;
}
}
Could you flip the array and then search directly?
$flipped = array_flip($user_location);
$user_id = isset($flipped[$location]) ? $page[$flipped[$location]] : $user_gen;
If the array is flipped, you can see what key $location
represents and use that as the index on $page. If it's not set, it'll default to $user_gen as above.
I would use array_search for this:
$user_id = $user_gen;
$user_id_index = array_search($location, $user_location);
if (false !== $user_id_index) {
$user_id = $page[$user_id_index];
}