Extract value from array then run if on value - php

I have an array of items (cheese) in a checkbox format like so
array(
'type' => 'checkbox',
"holder" => "div",
"class" => "",
"heading" => __("Choose your cheese topping", 'rbm_menu_item'),
'param_name' => 'cheesbox',
'value' => array( 'Cheddar'=>'Chedder', 'Gouda'=>' Gouda', 'Bleu'=>' Bleu'),
"description" => __("<br /><hr class='gduo'>", 'rbm_menu_item')
),
The values of the array are displayed on a page (in a hidden div) using the heredoc declaration with an if to check if the checkbox has been used - if the return is empty the div does not show - if one of the checkboxes is "checked" then it does.
///Cheese selections
if (!empty($cheesbox)) {
$output .= <<< OUTPUT
<br />
<div class="sides">Comes with: <p>{$cheesebox}</p></div>
<br />
OUTPUT4;
}
What I need to do is pull any one of the values in the array and if its in the $cheesebox the do something.
Ive tried using an ifelse like this
if ( ('$cheesebox') == "Cheddar" ){
echo "Your topping is Cheddar";
}
elseif ( ('$cheesebox') == "Gouda" ){
{
echo "Your topping is Gouda";
}
elseif ( ('$cheesebox') == "Bleu" ){
{
echo "Your topping is Bleu";
}
however this does not work - I'm sure I have it wrong somehere along the line or does the heredoc function only allow for one?
if so is there a way to accomplish this?

Single quotes in PHP mean a literal string with no parsing of variables. Try this:
if ($cheesebox == "Cheddar") {
echo "Your topping is Cheddar";
} else if ($cheesebox == "Gouda") {
echo "Your topping is Gouda";
} else if ($cheesebox == "Bleu") {
echo "Your topping is Bleu";
}
Better yet:
if (in_array($cheesebox, ['Cheddar', 'Gouda', 'Bleu'])) {
echo "Your topping is {$cheesebox}";
}
EDIT: In response to your further requirements in the comments:
In your PHP:
$cheeses = ['Cheddar', 'Gouda', 'Bleu'];
$cheeseBoxes = '';
foreach ($cheeses as $cheese) {
$cheeseClass = $cheesebox == $cheese ? '' : 'cheese-hidden';
$cheeseBoxes .= <<<CHEESE
<div class="cheese {$cheeseClass}">
<p>Cheese: {$cheese}</p>
<img src="/images/cheeses/{$cheese}.png" alt="A picture of some {$cheese}" />
</div>
CHEESE;
}
// Then, wherever you need it, or just use $cheeseBoxes in your chosen heredoc:
echo $cheeseBoxes;
In your CSS, to hide the inactive ones:
.cheese.cheese-hidden {
display: none;
}

Related

PHP: REQUEST_METHOD as basic error handling for html form

I am using input from a html form to output arrays containing the value inputted. I would like to carry out basic error handling that states what fields were left empty, a error message if no fields are inputted and then if all of the fields are inputed. However, my code isn't doing as I would like. It works elsewhere in my code but I can not figure out the difference.
EDIT:
I am getting "Notice: Undefined index: ageChoice" and "Notice: Undefined index: colourChoice"
HTML
<form action="profileFilter.php" method="POST">
<p>Age: <br>
<input type="radio" name="ageChoice" value="1">1
<input type="radio" name="ageChoice" value="2">2
<p>Colour: <br>
<input type="radio" name="colourChoice" value="Tabby">Tabby:
<input type="radio" name="colourChoice" value="Ginger">Ginger
<input type="submit" name="button">
</form>
ProfileArray.class.php
class ProfileArray {
Public function dataArray() {
$profileArray = array(
array( 'Name' => 'Toby',
'Age' => 3,
'Colour' => 'Ginger',
'Gender' => 'Male',
'Personality' => 'Gentle',
),
array( 'Name' => 'Cassie',
'Age' => 2,
'Colour' => 'Tabby',
'Gender' => 'Female',
'Personality' => 'Playful',
),
);
return $profileArray;
}
}
profileFilter.php
include ("ProfileArray.class.php");
$object = new ProfileArray();
$profileArray = $object->dataArray();
if($_SERVER["REQUEST_METHOD"] == "POST") {
$passedAgeChoice = $_POST['ageChoice'];
$passedcolourChoice = $_POST['colourChoice'];
$errorMessage = "";
if (!empty($passedAgeChoice)) {
echo $errorMessage = "WARNING: You have not entered an age to search for<br>";
}
if (!empty($passedColourChoice)) {
echo $errorMessage = "WARNING: You have not entered a colour to search for<br>";
}
if ($errorMessage == TRUE) {
echo '<h4 class="error">You have inputted nothing to search for</h4> Go back and try again';
}
//If there are no errors submit the form
if ($errorMessage == "") {
echo '<h4 class="error">Here are your full search results</h4> Back to Homepage<br>';
}
}
Use isset() and !isset() for everything here and you won't get any warnings. As I mentioned in comments, isset() is best used for radio buttons (and checkboxes).
empty() is mostly used for string inputs, lengths etc.
Sidenote: $passedcolourChoice has also been replaced with $passedColourChoice.
Variables are case-sensitive.
You can omit $passedAgeChoice = $_POST['ageChoice'];
$passedcolourChoice = $_POST['colourChoice']; and use the below:
if(isset($_POST['ageChoice'])){
$passedAgeChoice = $_POST['ageChoice'];
}
if(isset($_POST['colourChoice'])){
$passedColourChoice = $_POST['colourChoice'];
}
$errorMessage = "";
if (!isset($passedAgeChoice)) {
echo $errorMessage = "WARNING: You have not entered an age to search for<br>";
}
if (!isset($passedColourChoice)) {
echo $errorMessage = "WARNING: You have not entered a colour to search for<br>";
}
if ($errorMessage == TRUE) {
echo '<h4 class="error">You have inputted nothing to search for</h4> Go back and try again';
}
In profileFilter.php change two lines
$passedAgeChoice = (isset ($_POST['ageChoice'])) ?$_POST['ageChoice']:'';
$passedcolourChoice =(isset ($_POST['clourChoice'])) ? $_POST['colourChoice']:'';
Best practice: don't use global variables (e.g. $_POST, $_GET) directly. Try to validate them before use.

What is the character returned from "\n\n" when exploded with respect to "\n" using PHP?

I have added some data in a DB. The text contains both English and Arabic. So, while I need to display the text in webpage, I am trying to split the total text into paragraphs.
Then if a paragraph contains Arabic text, I am displaying the text
in a div with "right-to-left" alignment.
If the text is in English, it is displayed in "left-to-right" alignment.
So here's is my following code:
/*------ Allign text ------*/
function align_text($text)
{
$string = $text;
$returnString = '';
$paraArray = explode("\n", $string);
if(count($paraArray) > 0)
{
foreach($paraArray as $pa)
{
$isRight = $this->is_rtl($pa);
if($isRight)
{
$para['para'] = $pa;
$para['align'] = 'R';
}
else
{
$para['para'] = $pa;
$para['align'] = 'L';
}
$paraArr[] = $para;
}
}
else
{
}
return $paraArr;
}
function is_rtl($string)
{
$rtl_chars_pattern = '/[\x{0590}-\x{05ff}\x{0600}-\x{06ff}]/u';
return preg_match($rtl_chars_pattern, $string);
}
Now, here is the problem.
Array (
[0] => Array (
[para] => This is testing mail.
[align] => L )
[1] => Array (
[para] => This is testing mail. This is testing mail. This is testing mail.
[align] => L )
[2] => Array (
[para] =>
[align] => L )
[3] => Array (
[para] => This is testing mail.
[align] => L ) );
As you can see, the 2nd row(if counted from 0th row) has { [para] => }.
That is because of "\n\n" i.e. two consecutive newlines or <enter>.
What is the character that I am getting here?
When trying to display the result like this,
<?php
if(!is_array($row['chatDesc']))
{?>
<div class="com-text">
<?php echo $row['chatDesc'];?>
</div>
<?php
}
else
{
foreach($row['chatDesc'] as $rC)
{
echo strlen($rC['para']);
if(strlen($rC['para'])==1 &&
($rC['para']==null || $rC['para']=="" || $rC['para']==" " || $rC['para']=="\n"))
{?>
<div class="com-text" style="direction:rtl; clear:both">
[AAA<?php echo $rC['para'];?>AAA]
</div>
<?php
}
else if($rC['align']=='R' && $rC['para']!=' ')
{?>
<div class="com-text" style="direction:rtl; clear:both">
[<?php echo $rC['para'];?>]
</div>
<?php
}
else if($rC['align']=='L' && $rC['para']!=' ')
{?>
<div class="com-text" style="direction:ltr;clear:both">
[<?php echo $rC['para'];?>]
</div>
<?php }
}
} ?>
I am unable to determine the { [para] => }.
I am never getting this div displayed:-
<div class="com-text" style="direction:rtl; clear:both">
[AAA<?php echo $rC['para'];?>AAA]
</div>
But if I change the condition,
if(strlen($rC['para'])==1 &&
($rC['para']==null || $rC['para']=="" || $rC['para']==" " || $rC['para']=="\n"))
to only if(strlen($rC['para'])==1), the div is getting displayed.
The content of the div is [AAA AAA]. There is an extra space between the pairs of AAA. If this character is indeed a <space> then why the initial condition in the if statement isn't satisfying?
I've tried the if statement you've provided with the \n\n, however, it worked fine for me. As a solution that will fix all the white space characters, I've done some refactoring of your function to remove any unnecessary white spaces from your paragraph and only push it to the array if the paragraph is not empty.
function align_text($text){
$result = array();
foreach(explode("\n", $text) as $paragraph){
// Remove any whitespace from the beginning and end of the paragraph
$paragraph = trim($paragraph);
// Only append the paragraph if it's not empty
if(strlen($paragraph) > 0)
array_push($result, array('para' => $paragraph, 'align' => is_rtl($paragraph) ? 'R' : 'L'));
}
return $result;
}
And you don't need that many if cases to display your divs in your HTML:
<?php foreach($row['chatDesc'] as $rC): ?>
<div class="com-text" style="direction:<?php echo $rC['align'] == 'L' ? 'ltr' : 'rtl' ?>;clear:both;">
<?php echo $rC['para']; ?>
</div>
<?php endforeach; ?>
Also, if you only use the align for the div alignment, you could also set it to ltr or rtl directly in your align_text function.
array_push($result, array('para' => $paragraph, 'align' => is_rtl($paragraph) ? 'rtl' : 'ltr'));
Then in your html, you could simply echo the align:
<?php foreach($row['chatDesc'] as $rC): ?>
<div class="com-text" style="direction:<?php echo $rC['align'] ?>;clear:both;">

Creating code logic that uses a for loop to cycle through several arrays

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);
}

How to make multiple checkboxes work with php and sql

How would I pass an array of multiple checkboxes and values through php, saving to a sql database, as well as being able to pull up the saved data back on the client side?
For example, I have an array that saves checkbox values in the way of '"checked"""checked""""', but not only do I want to save the checked value, I also want to save the form data, as follows :
Apples : Checked
Oranges : Not Checked
Bananas : Checked
Tomatoes : Checked
Any help would be GREATLY appreciated, please answer with context of how to do, not just code - still learning!
Here is the code THAT WORKS for this question
processing code :
$salesman = $data['data-invoice-salesman']; // this is an array
$salesman_array = array(); // create new array
$salesman_names = array(1 => "User1",2 => "User2",3 => "User3",4 => "User4",5 => "User");
for($i = 1; $i <= 5; $i++){ // loop from 1 to 5
if(in_array($i, $salesman)){ // if value exists (has been selected), stack 'checked', if not, stack ''.
$salesman_array[$salesman_names[$i]] = "checked";
} else {
$salesman_array[$salesman_names[$i]] = "";
}
}
$salesman_json = mysqli_real_escape_string($this->_con, json_encode($salesman_array)); // encode the array into JSON and then escape it.
form code THAT WORKS :
<?php
$salesmand = json_decode($invoice['Invoice']['salesman'], true);
$salesman_names = array(1 => "User1",2 => "User2",3 => "User3",4 => "User4",5 => "User5");
foreach ($salesman_names AS $i => $name) {
if ($salesman[$name] == "checked") {
echo '<input type="checkbox" name="data-invoice-salesman[]" value="'.$i.'" checked/> '.$name.'<br>';
} else {
echo '<input type="checkbox" name="data-invoice-salesman[]" value="'.$i.'" /> '.$name.'<br>';
}
}
?>
</div>
Add an array that maps the indexes to the name:
$salesman_names = array(
1 => "Joe Smith",
2 => "Fred Flintston",
3 => "George Jetson",
4 => "John Hamm",
5 => "Alan Smithee"
);
Then in your loop, you can do:
$salesman_array[$salesan_names[$i]] = "checked";
The JSON that's saved in the database might then look like:
{"Joe Smith":"checked", "Fred Flintson": "", "George Jetson","checked", "John Hamm":"", "Alan Smithee":""}
To display the checkboxes, you would refer to the $salesman_array when displaying it:
$salesman = json_decode($invoice['Invoice']['salesman'], true);
foreach ($salesman_names AS $i => $name) {
if ($salesman[$name] == "checked") {
echo '<input type="checkbox" name="data-invoice-salesman[]" value="'.$i.'" checked/> '.$name.'<br>';
} else {
echo '<input type="checkbox" name="data-invoice-salesman[]" value="'.$i.'" /> '.$name.'<br>';
}
}

Passing selected checkbox value array?

I have a checkbox down below...
It is in the loop :
<script>
function checkCheckBoxes_abel() { //check if the checkbox is checked before submitting.
if (document.payform.pay_checkbox.checked == false)
{
alert ('You didn\'t choose any of the checkboxes for payment !');
return false;
}
else
{
alert ('One or more checkboxes from payment form are checked!');
document.forms["payform"].submit();
return true;
}
}
</script>
<form name="payform" onsubmit="return checkCheckBoxes_abel();" method="POST" action="payment.php">
for($record_count=0;$record_count<$record;$record_count++)
{
<td><input type="checkbox" name="pay[]" id="pay_checkbox" value="<?php echo $amount_dueArr[$record_count];?>" onClick="checkTotal()"/></td>
}
</form>
How can I pass the value of the checkbox that is being selected ?
Thanks
can I do :
if (isset($_POST['pay']))
{
foreach($_POST["eg_payamt_"] as $key => $payamt){
echo "eg_payamt_$key => $payamt\n <br>";
}
}
on payment.php ?
Thanks
An illustration :
I have three checkboxes...
If I check one of the checkbox,
Checkbox ticked on : Array
and if I'm not checking any of them
Checkbox ticked on :
Which is correct, but the content of the Array is not only one but three of them,
How can I make it only one ? or only two ? depends on how many checkboxes are being checked.
can I do it on another field ?
it seems that it works only for one field
if (isset($_POST['pay']))
{
if(is_array($_POST['pay']))
{
//foreach($_POST["pay"] as $key => $desc)
foreach($_POST["eg_description_"] as $key => $desc)
{
echo "eg_description_$key => $desc\n <br>";
}
}
else
{
//echo 'description :'.$_POST['pay'];
echo 'description :'.$_POST["eg_description_"];
}
}
there are 2 types of values will receive in POST, if someone selects only one checkbox that will throw warning in foreach loop so you can try this way
if (isset($_POST['pay']))
{
if(is_array($_POST['pay'])) {
//foreach($_POST["eg_payamt_"] as $key => $payamt){
foreach($_POST["pay"] as $key => $payamt){
echo "eg_payamt_$key => $payamt\n <br>";
}
}
else {
echo 'pay : '. $_POST['pay'];
}
}
Check these -
http://www.kavoir.com/2009/01/php-checkbox-array-in-form-handling-multiple-checkbox-values-in-an-array.html
http://www.html-form-guide.com/php-form/php-form-checkbox.html

Categories