Advanced PHP foreach() loop..(nested if/else) - php

I'm having a bit of a brain-fart here...lol
I was using a forloop() initially for this.. but then the conditions got a bit more advanced on things I needed to check for, as well as the output based on found/not found..
My problem is ensuring that on consecutive loops.. the 'else' on the (no access) potion only gets echo'd once... but of course on every 'loop' it will check from the top and if not a match output the 'no-access' text.. (on every iteration).. where it should only output once.
Originally there was only a few if() statement/checks in the foreach() loop.. where a simple break; took care of things fine...
but these if()'s turned into if/else.. which means the else will get 'triggered' on the next 'loop'.. how can this be prevented?
$arrwebinars = ("Name1", "Name3");
foreach($arrwebinars as $webinar) {
/* Webinar 1 */
if($webinar == 'Name1') {
if($web01_title != '') {
echo "available";
} else {
echo "not available";
}
} else {
echo "no access";
}
/* Webinar 2 */
if ($webinar == 'Name2') {
if ($web02_title != '') {
echo "available";
} else {
echo "not available";
}
} else {
echo "no access";
}
/* Webinar 3 */
if ($webinar == 'Name3') {
if($web03_title != '') {
echo "available";
} else {
echo "not available";
}
} else {
echo "no access";
}
}
is there some other sort of 'control' I can use to ensure the main if/else only gets executed once?
Sorry , I am having a hard time trying to describe this one, hopefully the code explains it all (and the problem)
thanks.
update:
Current State: reverted back to foreach() loop.
User is only authorized for 2 vids (#5 & #6 we'll say..can be any of the 6 in reality)
Upon first loop/iteration.. vids 1-4 output (no access for you!) (because they dont, only #5 & #6 as stated above)
no. 5 outputs the embed code fine (access)
no. 6 says 'No access for you'.. (even though they do/should have access)
Upon the scond iteration..vids 1-4 are duplicated, and again say "No access for you" (outside of it being a duplication..this is correct).. however, vid #5 NOW says "no access for you" (first loop it outputted fine, second loop it is looking for a new 'match' while not what I want.. in theory this is correct.. but should have a duplicate)
Vid #6 is NOW outputting the embed code (where as on first loop it did not)..
The user has only purchased access to 2 vids.. so the loop only happens twice.
but I get '12' echo's
No matter what I should only get 6 echo's with 1 out put per video (available/not available -or- no access)
I cant seem to wrap my head around this today.. :(
Goal I want achieve:
6 outputs TOTAL
each output (echo) should ONLY have:
available or not available printed (this is the nested conditional check for the blank title)
-or-
no access
there are 6 video to check against.
the user can have purchased access to 1 or up to all 6 vids
first check is: is the webinar name in their purchased array found in the total available 6 vids available
second tier conditional check:
if YES (match found == access)...then check to see if the title is missing (if there output access [video embed code]... if not there output text 'not available yet')
(going back to first conditional check) if there is NO ACCESS (match not found).. output 'no access' text.
This works if I wanted duplicates on the stage/page.. (but I dont!) LOL..
I need to be limited to ONLY 6 outputs,.. as there are only a total of 6 vids available.
I DO NOT WANT:
on loop 1 it outputs access for vid#1 and #2-#6 are no access..
on loop 2 it re-states all of these outputs, has vid#1 no-access now, vid#2 has access and vids #3-#6 are no access...
etc.etc.. and the cycle continues. I'm getting lost on this one!..
thanks!

If you wish to stop considering that "row" when you encounter a "no access" then you could simply continue; after each no-access. or do you wish to check the others even if you encounter "no access" on the first, just to fail silently in that case?

Not sure exactly what you're trying to achieve, but your code could be shortened greatly.
$webinars = array('one', 'two', 'Name3');
$web0_title = 'not empty'; // Just a demo
for ( $i = 0; $i < count($webinars); $i++ )
{
$access = FALSE;
$available = FALSE;
$name = 'Name' . $i;
$title = 'web' . $i . '_title';
if ( $webinars[$i] == $name ) {
if ( ! empty( $$title ) ) {
$available = TRUE;
}
$access = TRUE;
}
// Simple debug, not sure what you want to accomplish
echo 'Webinar: ' . $webinars[$i] . ' <br />';
echo 'Availability: ' . ( $available ? 'Available' : 'Not Available' ) . '<br />';
echo 'Access: ' . ( $access ? 'Access' : 'No Access' ) . '<br /><br />';
}
Edit: Just read your comments so I updated it.

Related

IF statement won't take more than 2 conditions

I'm setting up a system where if a users group number is present the user will have access to the page. For example I want people in group 7,8, and 14 to have access to the page. This works fine for the users in group 7 and 8 but if the user is group 14 access appears to be denied. Here's what I tried so far I tried to go this two ways but to no avail. Any help would be appreciated.
An if statment with more than two conditions.
if ($_SESSION['userrole'] == 8 || $_SESSION['userrole']== 7 || $_SESSION['userrole']== 14) {
//text
}else{
echo "access denied";
An array that have values to check against
$acc = array("8","7","14");
if (in_array($_SESSION['userrole'],$acc)){
//text
}else{
echo "access denied";
as Syscall mentioned in his comment you are trying to look for the value "2,14"
in array contain values like this array("8","7","14");
this is want work
what you need to do in this case is use explode()
in your scenario, it will look like this
$acc = array("8", "7", "14");
$user_group = explode(',',$_SESSION['userrole']);
foreach ($user_group as $group) {
if (in_array($group, $acc)) {
//text
} else {
//text
}
}

Why aren't my PHP error messages working correctly?

I'm creating a basic form to purchase adult & child tickets from. With the way the form is set up, the user must purchase an adult ticket, but they don't need to purchase a child ticket. I've added some error messages/validations to enforce rules within the form. All of the adult ticket error messages work correctly, but the child ones aren't working right.
I want the child ticket rules to check the following: that a valid number (aka not a letter) has been entered, the quantity is greater than 0, and a whole number has been entered. I thought I had the rules set so they only start validating if the child ticket input is not empty, but instead they're still trying to validate when it is empty, which I don't want it to do considering no child tickets need to be purchased. How do I get this to work correctly?
Here is my PHP code with the error messages.
<?php
$adult=$_POST['adult'];
$child=$_POST['child'];
$date=date('m/d/Y');
function isInteger($input) {
return(ctype_digit(strval($input)));
}
if (empty($adult)) {
$error_message='You must purchase at least 1 Adult ticket!';
}
else if (!is_numeric($adult)) {
$error_message="You must enter a valid number!";
}
else if ($adult <= 0) {
$error_message="You must enter a quantity greater than zero!";
}
else if (!isInteger($adult)) {
$error_message="You must enter a whole number for the quantity! (i.e. 1, 2, etc...)";
}
else if (!empty(!is_numeric($child))) {
$error_message="You must enter a valid number!";
}
else if (!empty($child <= 0)) {
$error_message="You must enter a quantity greater than zero!";
}
else if (!empty(!isInteger($child))) {
$error_message="You must enter a whole number for the quantity! (i.e. 1, 2, etc...)";
}
else if ($adult + $child > 5) {
$error_message="Sorry, there is a limit of 5 total tickets per customer!";
}
else {
$error_message='';
}
if($error_message !=""){
include('index.php');
exit();
}
?>
If $child = 1
if(!empty($child <= 0) ) is equivalent to if(!empty(false)) which makes no sense.
Same with (!empty(!is_numeric($child)))
Use if(isset($child) && $child <= 0) {} instead
You can also use $child = isset($_POST['child']) ? $_POST['child'] : 0
Not looking for an accepted answer, just wanted to suggest a more practical approach.
PHP has some very powerful built-in functions for validation. Two you can use are filter_var and filter_input, which can easily validate numeric values as integers, without needing to check each variation of an integer.
Additionally instead of chaining several elseif conditions, I suggest using throw to immediately raise an Exception that needs to be handled, otherwise halting execution at that point. Accompanied within a try/catch block to handle the exception as desired.
Example https://3v4l.org/PJfLv
$adult = filter_var($_POST['adult'] ?? null, FILTER_VALIDATE_INT);
$child = filter_var($_POST['child'] ?? null, FILTER_VALIDATE_INT);
try {
if (false === $adult || false === $child) {
throw new \InvalidArgumentException('You must enter a whole number (1, 2, etc...)');
}
if (0 >= $child || 0 >= $adult) {
throw new \InvalidArgumentException('You must enter a quantity greater than zero!');
}
// at this point child and adult must be >= 1
// ensure total is at least 1 and at most 5
$total_options = ['options' => ['min_range' => 1, 'max_range' => 5]];
$total = filter_var($adult + $child, FILTER_VALIDATE_INT, $total_options);
if (false === $total) {
throw new \InvalidArgumentException('Sorry, there is a limit of 5 total tickets per customer!');
}
// what should happen next...
} catch(\InvalidArgumentException $e) {
$error_message = $e->getMessage();
require __DIR__ . '/index.php';
## always use absolute paths to prevent include_path overrides/overhead
} finally {
// do something else no regardless of success or Exception...
}
For PHP < 7.0 replace
$_POST['child']) ?? null
with
isset($_POST['child']) ? $_POST['child'] : null

Iterate through array when item is found end loop but not found call function

Hi all I have a question. I have an array that is dynamically populated. In the array there are 2 main types of items. Item with file name that equals 27 characters and the rest are either more or less. I am able to separate the 2 two types. The second list is added to a new array called $usedArray. Those items are then iterated through and the file name is substringed from character 0,6 to be used to compare the enduser's input on the page.
if the item is found in that array it will fire a function to send them a text and a email of the the full file name. my problem is if the item is not found until x iterations, it would fire the not found function x amount of times, and if it's not found at all it does the same thing. If I have 99 items that do not match it fire 99 times. to stop from firing I left the not found to just printing not found on the screen. I thought of calling the notfound function outside the loop but do not want it to fire if an items is found
This is my code I have so far
do{
if (substr($val,0,6) == $studentID)
{
$codeFound = substr($val,22,19);
print_r($studentID . ' is found <br /> Their code is ' . $codeFound);
//sendText($phoneNum,$codeFound,$messageMonth);
//sendEmail($emailInfo,$messageMonth,$codeFound);
break 1;
}
else
{
print_r($studentID . " was not found <br />");
}
} while(list(, $val) = each($usedArray));
This is my output
166003 was not found
166003 was not found
166003 was not found
166003 is found
Their code is xxxxxxxxxx
I think you should add a flag to track if you have found something or not:
$item_found = false;
do{
if (substr($val,0,6) == $studentID)
{
$codeFound = substr($val,22,19);
print_r($studentID . ' is found <br /> Their code is ' . $codeFound);
//sendText($phoneNum,$codeFound,$messageMonth);
//sendEmail($emailInfo,$messageMonth,$codeFound);
// item found!
$item_found = true;
break 1;
}
} while(list(, $val) = each($usedArray));
// now check - if `$item_found` is false
// then you can send your NotFoundEmail
if (!$item_found) {
sendNotFoundEmail();
}

php echo not working after elseif

I am trying to extract data from an XML file using simplexml. I am running a series of while and foreach loops to dig down to what I need.
However, I have found that after the elseif is finished I can no long display additional data to the screen (echo and print_r don't work). I have attached a code snippet for the elseif loop through the end of the end of the script. Please excuse the lousy code, I am a relatively new programmer.
elseif ($select_vars[1]==-1) {
$sub1=0;
$sub2=0;
$temp_count = 1;
$modnum=intval($select_vars[0]);
$sub1m = $xmls->module->{
intval($select_vars[0])}
->count();
while ($sub1 < $sub1m) {
foreach($xmls->module->{
$modnum}
->sublist1->{
$sub1}
as $hit2){
$sub2m = $xmls->module->{
$modnum}
->sublist1->{
$sub1}
->count();
while ($sub2 < $sub2m) {
foreach($xmls->module->{
$modnum}
->sublist1->{
$sub1}
->sublist2->{
$sub2}
as $hit3){
$template_string .= $temp_count . " - " . (string)$hit3 . "<br/>";
$temp_count = $temp_count+1;
$template_list[] = (string)$hit3;
}
$sub2 = $sub2+1;
}
$sub1 = $sub1+1;
$sub2 = 0;
}
}
echo "sub1 = " . $sub1 . "<br/>";
}
echo "here <br/><br/>".$template_string;
print_r ($template_list);
$template_list = array_unique($template_list);
sort($template_list);
print_r ($template_list);
I know the loops extract the right information because I can echo anywhere in the various loops except after the esleif closing bracket.
A live copy of the code is available at: http://www.aquilasolutions.us/software/templates/pages/filter-list.php
EDIT:
The output SHOULD be 3 selects and when the top box is filled when the others are empty a series of line (up to 400+) in the format ### - ####-####-####-#### should appear.
EDIT 2:
To View the error:
1. set select "Module " to be anything
2. Set select sublist 1 and sublist 2 to be empty
3. Make sure the array at the top has 3 keys (it represents a session cookie called filter-list and represents the selected items)
EDIT 3:
I have tracked down the error but not been able to resolve it.
There is a fatal error in my log (Fatal error: Call to a member function count() on null) on the line:
$sub2m = $xmls->module->{$modnum}->sublist1->{$sub1}->count();
I tried putting an isnull catch in but then there was a fatal error on the isnull....
I tracked down the issue and as expected it was my own stupidity!
I typed the wrong variable for the while ($sub2 < $sub2m) loop.
It SHOULD have been while ($sub2 < $sub2num)

php memcache to store repeated keys for different values

I've been working with PHP (I'm very new to this) and I have this scenario:
I have a list with 3 (or more) IP addresses + ports that comes from a file, so each line of my file has:
192.168.3.41:8013
192.168.3.41:8023
192.168.3.41:8033
So in my array, these are elements array[0], array[1], array[2]. The purpose of the application is simple, ping the IP:PORT and know if it is responding and how many ping errors it has. But that is not all, I have to count the time it takes to do the process for 3 minutes and 1 minute. So, I've been asked to work with MemCache to do the following:
For each IP:PORT, I need to save in MemCache how many errors does I have in 3 minutes as well as the number of errors I have in 1 minute, so something like that:
For number of errors in 3 minutes
Map<Key, Value> = Map<IP:PORT, NumberOfErrors3Mins>
For number of errors in 1 minute
Map<Key, Value> = Map<IP:PORT, NumberOfErrors1Min>
So, a data sample could be like this:
For 3 minutes:
<192.168.3.41:8013, 5>
<192.168.3.41:8023, 2>
<192.168.3.41:8023, 0>
For 1 Minute:
<192.168.3.41:8013, 3>
<192.168.3.41:8023, 1>
<192.168.3.41:8023, 1>
So, I have two maps and 3 entries for each map. I'm pretty new to PHP and MemCache is kind of difficult to me, the logic I stablished is the following:
$array = array('192.168.3.41:8013','192.168.3.41:8023','192.168.3.41:8033');
for ($i = 0; $i < count($array); ++$i){
$currentProxy = $array[$i];
echo "working on $i : <br/>";
echo "good to see you friend:".$currentProxy."<br/>";
$res1 = $memt1->get($currentProxy);
$res2 = $memt2->get($currentProxy);
echo "response for proxy:".$res1."<br/>";
echo "response for proxy:".$res2."<br/>";
if (!$res1){
echo "Does not exist - create<br/>";
$memt1->set($currentProxy, 1, null, 0);
} else {
echo "Does exist - help<br/>";
$memt1->increment($currentProxy);
}
if (!$res2){
echo "Does not exist - create<br/>";
$memt2->set($currentProxy, 1, null, 0);
} else {
echo "Does exist - help<br/>";
$memt2->increment($currentProxy);
}
}
The problem I am facing is that both memt1 and memt2 are referring to the same, for instance, if I increment <192.168.3.41:8013> for memt1, it also increment it for memt2, I think that this could be a very noob question, but I've just entered to PHP world and I don't know how to handle this at all, this is what I tried, if somebody could help me, please I would be really grateful. Thanks in advance.
I did it, it was simplier of what I thought before:
Basically, one MemCache for all the type of possible keys with values, I didn't know how to use it well, but now it works and fits perfect for me, hope it helps somebody who is starting with this:
$memHandler = new MemCache();
if ($memHandler) {
$memHandler->connect('localhost','11211');
} else {
die('Problem with MemCache');
}
$array1 = $memHandler->get('e1');
$array3 = $memHandler->get('e3');
$lcr1 = $memHandler->get('lcr1');
$lcr3 = $memHandler->get('lcr3');
if (!$array1) {
echo 'Does not exist - create<br/>';
$memHandler->set('e1', $newArray);
} else {
echo 'Does exist<br/>';
foreach ($array1 as $key => $value) {
echo $key.':'.$value.'<br/>';
}
}
if (!$array3) {
echo 'Does not exist - create<br/>';
$memHandler->set('e3', $newArray);
} else {
echo 'Does exist<br/>';
foreach ($array3 as $key => $value) {
echo $key.':'.$value.'<br/>';
}
}
echo '=============================<br/>';
if (!$lcr1){
echo 'Does not exist - create date<br/>';
$memHandler->set('lcr1', time());
} else {
echo 'Does exist<br/>';
echo $lcr1.'<br/>';
}
if (!$lcr3){
echo 'Does not exist - create date<br/>';
$memHandler->set('lcr3', time());
} else {
echo 'Does exist<br/>';
echo $lcr3.'<br/>';
}

Categories