I'm trying to build a custom zip code search to find a delivery fee, but I can't seem to get it right.
First up this is how I have my form set up on the front-end:
<form class="delivery-fee" role="search" method="get" action="">
<div class="form-group">
<label>Find Your Delivery Area:</label>
<input class="form-control" type="number" value="" name="zipcode" placeholder="Enter Zipcode" pattern="\d*" />
<input type="submit" value="See Delivery Minimum" />
</div>
</form>
I've got my data set up like this:
$delivery_areas = [
'Rancho Cucamonga' => [
'zipcodes' => [91701, 91729, 91730, 91737, 91739],
'fee' => 100
],
'Upland' => [
'zipcodes' => [91784, 91785, 91786],
'fee' => 150
]
];
This is how I'm looping through my data:
foreach ($delivery_areas as $key => $delivery_area) {
if (is_array($delivery_area)) {
if (in_array($_GET['zipcode'], $delivery_area['zipcodes'])) {
echo $delivery_area['fee'];
} else {
echo 'Error message';
}
}
}
The problem I'm having is if I do a search for say 91701 I do get the correct fee returned, but I'm also getting the error message with it. On the flip side I'll also get two error messages if nothing is found.
Any suggestions on how I could get the desired result?
You can adapt your code by using a var, e.g.:
$fee = -1;
foreach ($delivery_areas as $key => $delivery_area) {
if (is_array($delivery_area)) {
if (in_array($_GET['zipcode'], $delivery_area['zipcodes'])) {
$fee = $delivery_area['fee'];
break;
}
}
}
if($fee == -1)
echo 'Error message';
else
echo $fee;
Test:
$fee = 0;
foreach ($delivery_areas as $key => $delivery_area) {
if (is_array($delivery_area) && in_array($_GET['zipcode'], $delivery_area['zipcodes'])) {
$fee = $delivery_area['fee']; break;
}
}
echo $fee!=0 ? $fee : 'Error Message';
Related
I'm trying to create a code logic by using a for loop instead of multiple if statements.
This is the previous if statement code I used before:
if (isset($_POST['answer1']))
{
if ($_POST['answer1'] === '1d')
{
print $correct[0];
}
elseif ($_POST['answer1'] === '1b')
{
print $incorrect[0];
}
elseif ($_POST['answer1'] ==='1c')
{
print $incorrect[0];
}
elseif ($_POST['answer1'] === '1a')
{
print $incorrect[0];
}
};
This code allows me to check for the answer and print either the $correct or $incorrect variable. My issue in this code is that it is very inefficient because I end up having to create ten or so if statements.
I came up with a mock-up of the for loop code to illustrate:
$_SESSION["totalCorrect"] = 0;
if (!isset($_SESSION["totalCorrect"]))
{
$_SESSION["totalCorrect"] = 0;
}
else
{
$totalCorrect = $_SESSION["totalCorrect"];
}
$postAns = array($_POST['answer1'] as $ans1, $_POST['answer2'] as $ans2, $_POST['answer3'] as $ans3, $_POST['answer4'] as $ans4, $_POST['answer5'] as $ans5, $_POST['answer6'] as $ans6,
$_POST['answer7'] as $ans7, $_POST['answer8'] as $ans8, $_POST['answer9'] as $ans9, $_POST['answer10'] as $ans10);
for ($i = 0; $i < count($postAns); i++)
{
if ($i == $postAns[])
{
if ($postAns[] === 'answer')
{
print $correct[];
$_SESSION["totalCorrect"]++;
}
else ()
{
print $incorrect[];
}
}
};
For this code, I have three arrays involved that I am trying to cycle through, $postAns, $correct, and $incorrect. The $correct and $incorrect arrays, when called, print out text depending on whether they got the answer right.
So for the for loop, I want to be able to cycle through each value of the $postAns array to check and and see which answer number it is and whether it is the correct answer or not. If it's correct, then the code cycles through $correct to get the right text for that answer number and increments the value of totalCorrect, the variable that stores how many the user got right. If incorrect, the code cycles through $incorrect to get the right text for that answer number.
I'm not really proficient with loops in general so any insight/help would be greatly appreciated.
EDIT: Included the form submission code
<form action="staff_info.php" method="get" id="q1">
<fieldset>
<legend>Question 1</legend>
<input type="radio" name="answer1" value="1a" id="1a"><label for="1a"> A. </label>
<input type="radio" name="answer1" value="1b" id="1b"><label for="1b"> B. </label>
<input type="radio" name="answer1" value="1c" id="1c"><label for="1c"> C. </label>
<input type="radio" name="answer1" value="1d" id="1d"><label for="1d"> D. </label>
<input type="button" id="answer" class="button " title="abutton" value="ANSWER">
NEXT
</fieldset>
The one thing you're missing in your pseudo code is the actual answers. If you create an array of correct answers as #fefe indicated then the loop will be something like this:
$correctAnswers = array(
'answer1'=>'1d',
'answer2' => '2b',
'answer3' => '3c',
'answer4' => '4b',
'answer5' => '5a'
);
$numberCorrect = 0;
$responseIndex = 0;
foreach ($correctAnswers as $key=>$answer) {
if ($_POST[$key] === $answer) {
$numberCorrect++;
print $correct[$responseIndex];
}
else {
print $incorrect[$responseIndex];
}
$responseIndex++;
}
I don't really know what you trying to achieve but the loop should look something like this and you can make some validation with if or switch case.
$postAns = array(
'answer1'=>'ans1',
'answer2' => 'ans2',
'answer3' => 'ans3',
'answer4' => 'ans4',
'answer5' => 'ans5',
'answer6' => 'ans6',
'answer7' => 'ans7',
'answer8' => 'ans8',
'answer9' => 'ans9',
'answer10' => 'ans9'
);
foreach ($postAns as $key=>$ans) {
var_dump($ans);
}
I'm trying to figure out how to get the right response from Multidimensional array in a SOAP request.
In fact, I would like to be able to Submit a "VAT" number and get the MULTISCORE value
functions.php
<?php
function score ($name)
{
$details=array(
array(
VAT=>"BE0422370068",
COMPANY=>"DEXIA",
MULTISCORE=>25,
CITY=>"HASSELT"
)
/*
array(
VAT=>"BE0402607507",
COMPANY=>"SCANIA",
MULTISCORE=>50,
CITY=>"BRUSSEL"
),
array(
VAT=>"BE0446140711",
COMPANY=>"DELHAIZE",
MULTISCORE=>50,
CITY=>"GENT"
)
*/
);
foreach($details as $va=>$var) //BTW
{
foreach($va as $co=>$cor) //COMPANY
{
foreach($co as $mu=$mur) //MULTISCORE
{
foreach($mu as $ci=<$cir) //CITY
{
if($name==$va) //If VAT exist
$score=$mur; //Show MULTISCORE value
}
}
}
}
return $score;
}
?>
These functions are called from following PHP request
Client.php
<?php
require 'lib/nusoap.php';
$client = new nusoap_client("http://localhost:8080/service.php?wsdl");
if (isset($_POST["cia"]))
{
$cia_name = $_POST["cia"];
}
if (!isset($_POST['submit'])) {
?>
<html>
<head>
<title>Scania Finance GRAYDON</title>
</head>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Company: <input type="text" size="12" maxlength="12" name="cia"><br /><br />
<input type="submit" value="submit" name="submit">
</form>
<?php
} else {
$response = $client->call('score',array("name"=>"$cia_name"));
if (empty($response))
echo "Please go <b>'Back'</b> and enter Company name";
else
echo "GRAYDON - MultiScore of Company $cia_name is equal to <b>".$response."</b></br></br>";
if ($response < '30'){
echo "SORRY, Graydon MultiScore is less than 30!";
} elseif ($response < '60'){
echo "CAN BE DISCUSSED, Graydon MultiScore is between 30 and 60, the visit of a Financial Salesman is needed!";
} else {
echo "GREAT, Graydon MultiScore is greater than 60, we can do Business together!";
}
}
?>
</body>
I can't find the way to call the right Array values.
You need to do two things.
1) in your function.php file write this line:-
$score = $details[$key];
return $score;
2) In your client.php file
$response is now Array so you need to print it via
print_r($response);
Now you can get MULTISCORE by $response['MULTISCORE'] and COMPANY NAME by $response['COMPANY'];
Note:- You wrote echo $response so you got only "Array" print.
Suggestion:- You should ON Error Reporting in developement mode otherwise you cannot debug code properly.
Write this line as:-
echo "GRAYDON - MultiScore of VAT ".$vat_num." is equal to <b>".$response['MULTISCORE']."</b></br></br>";
check new condion like this:-
if($response['MULTISCORE'] < '30'){
// your code
}
if you want company name then,
print company name:-
echo $response['COMPANY'];
You don't need to run foreach loop in this case. If you simply want MULTISCORE by submitting VAT value then it is very easy by below way:
refer array_search and array_column
function score ($name)
{
$details=array(
array(
'VAT'=>"BE0422370068",
'COMPANY'=>"DEXIA",
'MULTISCORE'=>25,
'CITY'=>"HASSELT"
)
/*
array(
'VAT'=>"BE0402607507",
COMPANY=>"SCANIA",
MULTISCORE=>50,
CITY=>"BRUSSEL"
),
array(
VAT=>"BE0446140711",
COMPANY=>"DELHAIZE",
MULTISCORE=>50,
CITY=>"GENT"
)
*/
);
$key = array_search($name, array_column($details, 'VAT'));
// $key = array_search('BE0402607507', array_column($details, 'VAT'));
$score = $details[$key]['MULTISCORE'];
return $score;
}
if you want all array values by submitting VAT then you need to write following line:-
$score = $details[$key];
return $score;
Now you will get company name by echo $score['COMPANY']; and multiscore by echo $score['MULTISCORE'];
Hope this will help you :)
Ok, anyway, I can't get it. As already said, tried several options as you asked but can't get the value only returns "Array".
For people are looking for how to retrieve one value of a multidimensional array using a SOAP request, to test it use XAMPP, here my work files on a PHPSOAP.zip
workfiles:
https://drive.google.com/file/d/0B-pCOHYZNf6COFNLdFV5RkpITGM/view?usp=sharing
Ravi Hirani thank you for your help!
I am trying to make a function so that if the user clicks the Update button AND the text in the textbox is a valid text(only the text from the array should be valid ie. text1, text2, text3). Then, it echo's the number assosiated to the text in the array so if text1 is entered, it should echo 10. I made a function to do it but it says Invalid argument supplied for foreach() on the foreach loop line.
HTML:
<input type='text' id='usertext' name='usertext' size='15' />
<input type='submit' name='update' id='update' value='Update' />
PHP:
public currenttext = 0;
$config['text'] = array(
10 => 'text1',
25 => 'text2',
50 => 'text3'
);
public function set_text($validtext) {
foreach($this->config['text'] as $key => $value) { // <-- foreach loop
if($key == $validtext){
$this->currenttext = $value;
}
}
}
if ($_POST['update') {
$this->set_text($_POST['usertext'));
}
You may try this:
if ( isset($_POST['update']) ) {
$this->set_text( $_POST['usertext'] );
}
Also flip the array;
$config['text'] = array(
'text1' => 10,
'text2' => 25,
'text3' => 50
);
Finally change the set_text method to something like this:
// $validtext could be text1 or text2 or text3 from user
public function set_text($validtext) {
if(array_key_exists($validtext, $this->config['text'])) {
$this->currenttext = $this->config['text'][$validtext];
}
}
Integrate these in your class properly, it'll work. Also check array_key_exists on PHP manual.
Actually, you dont need a foreach loop, alternatively, you could also use array_search() to get the same goal. Consider this example:
<?php
if(isset($_POST['update'])) {
$usertext = $_POST['usertext'];
$config['text'] = array(10 => 'text1', 25 => 'text2', 50 => 'text3');
$key = array_search($usertext, $config['text']);
if($key !== false) {
echo $key;
} else {
// not found
{
exit;
}
?>
<form method="POST">
<input type='text' id='usertext' name='usertext' size='15' /><br/>
<input type='submit' name='update' id='update' value='Update' />
</form>
Seems like the last stretch is getting harder!
So I have if statements and inside those statements code should execute if they are true. The problem is the code is executing even though its no true.
Code that execute even though Spproved is set to 1
if($user_data['permissions'] >= 1)
{
// If users permission is 1 or 2 they get a field for inputting the index # and a button to change the approve field from 0 to 1 may need to make a new field to record who approved it....
//Determine if the order is already approved. If not approved show index field and allow user to approve it with index number
if($data2[0]['Approved'] == 1)
{
echo " <font color=\"green\"> Approved";
}
else if($data2[0]['Approved'] == 0)
{
echo " Not Approved. Supply an index number and click approve to authorize this order to be completed.";
if (empty ($_GET) === false)
{
$required_fields = array('IndexNum');
foreach ($_GET as $key=>$value)
{
if (empty($value) && in_array($key, $required_fields) === true)
{
$errors[] = 'Fields marked with an asterisk are required';
break 1;
}
}
if (isset($_GET['success']) === true && empty($_GET['success']) === true)
{
echo 'Index has been updated and Order is now set to Approved';
}
else
{
if (empty($errors) === true)
{
$indexnum=$_GET['IndexNum'];
$approvedby=$user_data['lname'];
$vendorid1= $_GET['hidden1'];
update_approved($approvedby, $indexnum, $vendorid1);
header('Location: index.php');
exit();
}
else if(empty($errors) === false)
{
echo output_errors($errors);
}
}
}
?>
<form name="approveform" method="GET" action="">
<input type="hidden" name="hidden1" value="<?php echo $id;?>">"
Index Number*: <input type="text" name="IndexNum">
<input type="submit" value="Approve" action="">
</form>
<?php }
}
if($user_data['permissions'] == 2)
{
// If user is permission 2 they can have a button to say shipped... Do I need to record who shipped it? for now nah. Would be nice to input a data of arrival though. I will think on it .... pretty lazy
if($data2[0]['Approved'] == 1)
{
echo "<br/>";
echo "Confirm order has been ordered";
if(isset($_GET['Ordered']))
{
$vendorid1=$_GET['hidden1'];
echo $vendorid1;
//update_shipped($vendorid1);
//header('Location: index.php');
//exit();
}
?>
<form name="approveform" method="GET" action="">
<input type="hidden" name="hidden1" value="<?php echo $id;?>">
<input type="submit" name="Ordered" value="Ordered" action="">
</form>
<?php
}
}
IT shows Approved in green on the form and the Ordered button comes up fine. When I click the submit button the code in the else if($data[0]['Approved'] == 0) activates instead of the code the isset. Approved is set to 1 So I have no idea why that code is running.....
Value of print_r($data2) is
Array ( [0] => Array ( [VendorName] => Newegg [DateRequested] => 2013-09-25
[DateNeeded] => 0000-00-00 [Shipping] => Standard [VendorNumber] => 123123
[VendorFax] => NA [VendorAddress] => 1 ave new [VendorCity] => socorro
[VendorState] => nm [VendorZip] => 87114 [EquipmentConsumable] => Consumable
[GasType] => propane [GasLocation] => United States [UNMTag] => 0
[EquipmentLocation] => [index] => 414141 [totalcost] => 129.88
[Approved] => 1 [Shipped] => 0 ) )
Use strict comparisons, === and !== instead of == and !=. PHP tends to evaluate 1 and 0 as boolean unless told explicitly otherwise.
Also, with functions like empty(), you can change:
if( empty($_GET) === FALSE ) to if( !empty( $_GET ) )
if( empty($_GET) === TRUE ) to if( empty( $_GET ) )
As they return boolean.
Since you are using $_GET, make sure all the variables you need per pass are in the url. Since the form elements can only pass the nested input elements, you may require more hidden information to pass after submit. Also, you should probably put the file name in action="" or omit it from the form tag.
I know this is not going to solve your problem but....
You have an extra "
right here
|
V
<input type="hidden" name="hidden1" value="<?php echo $id;?>">"
Index Number*: <input type="text" name="IndexNum">
<input type="submit" value="Approve" action="">
<form action="http:\\127.0.0.1\rechecking.php" method="post" enctype="multipart/form- data"><pre>
Enter your first Name: <input type="text" name="fname" size="15"></input>
Enter your Last Name: <input type="text" name="lname" size="15"></input>
Your Email Id: <input type="text" name="email" size="15"></input>
Your age: <input type="text" name="age" size="1"></input>
Upload your Image: <input type="file" name="file"></input>
<input type="Submit" value="Submit"></input></pre>
</form>
<?php
if(!empty($_POST["fname"])&&!empty($_POST["lname"])&&!empty($_POST["email"])&&!empty($_POST["age"]))
{
if($_FILES["file"]["error"]>0)
{
echo $_FILES['file']['error'] ."error is there in uploading files";
}
}
else
{ $emt=array($_POST['fname']=>"Firstname",$_POST['lname']=>"LastName",$_POST['email']=>"Email",$_POST['age']=>"Age");
foreach($emt as $value=>$variable)
{
if(empty($value))
{
echo $variable." cannot be left blank<br />";
}
}
}
?>
The problem is that on leaving all the spaces blank in my formIts only showing the last ement of associative array.
For ex:-Leave firstname,lastname ,email, age then it will just show 'Age filed cannot be left blank'
Similarly if age is already filled in my input field then it will just show 'Email field can not be left empty'
Well I want it to display names of all fields that are left empty
You have to change $key and $variable:
$emt=array("Firstname"=>$_POST['fname'],"LastName"=>$_POST['lname'],"Email"=>$_POST['email'],"Age"=>$_POST['age']);
Change it as
$emt=array("Firstname"=>$_POST['fname'],"LastName"=>$_POST['lname'],"Email"=>$_POST['email'],"Age"=>$_POST['age']);
I think you're confusing:
foreach($emt as $value=>$variable)
{
with
foreach($emt as $variable=>$value)
(I would name the variable $variable $key instead, but's just a matter of taste)
And the same thing goes for the array which other answers has shown.
$emt = array(key => value, key => value, ....);
In order to check if a specific key is empty, you must make sure that it's set first (user can edit his HTML source and not send some field, triggering some warnings in your site).
Other than that, I find your code a little messy so you will find it difficult to debug or read after a while.
Here, I'm rewriting the PHP part to check the field is entered and is not empty.
<?php
$required = array(
'fname' => 'First name',
'lname' => 'Last name',
'email' => 'Email address',
'age' => 'Age',
);
$errors = array(); // Here, we store all the error messages. If it's empty, we are good to go.
foreach ($required as $key => $label) {
if (isset($_POST[$key]) || empty($_POST[$key])) {
$errors[] = "$label field is required.";
}
}
if (!isset($_FILES["file"])) {
$errors[] = 'Please upload an image';
}
elseif (isset($_FILES['file']['error']) && $_FILES['file']['error']) {
$errors[] = 'An error occurd while uploading your photo';
}
if ($errors) {
print '<ul>';
foreach ($errors as $error) {
print "<li>$error</li>";
}
print '</ul>'
}
else {
// All fields are filled and not empty, file is uploaded successfully. Process your form.
}
?>