This question already has answers here:
How can I check if an array element exists?
(8 answers)
Closed 8 years ago.
I have this PHP script:
for ($desc=1; $_POST['ddata'.$desc]; $desc++) {
if($_POST['ddata'.$desc]){
if ($desc == 1){
$ddata = $_POST['ddata'.$desc];
$dlocatie = $_POST['dlocatie'.$desc];
} else {
$ddata = $ddata.' / '.$_POST['ddata'.$desc];
$dlocatie = $dlocatie.' / '.$_POST['dlocatie'.$desc];
}
}
}
If I have 5 ddata fields, it gives this error: Undefined index: ddata6
How can I check if that fields exists so I can prevent this error?
How can I check if that fields exists so I can prevent this error?
use isset() to check if item exists prior accessing it.
Instead of if($_POST['ddata'.$desc]), you can do:
if(isset($_POST['ddata'.$desc]))
Or:
if(array_key_exists('ddata'.$desc, $_POST))
You can go for
if(isset($_POST['thekey']))
or more traditionally:
if(array_key_exists('thekey', $_POST))
Try
isset($_POST['ddata'.$desc])
Thanks
Check for what fields exist BEFORE you do your loop, by using preg_grep to scan the array for your ddata... fields.
$ddata_fields = preg_grep('/^ddata\d+$/', array_keys($_POST));
foreach($ddata_fields as $field) {
$ddata = $_POST[$field];
etc...
}
Just add a if(isset($_POST['ddata'.$desc])){} instead of if($_POST['ddata'.$desc]){}
Change the section beginning with...
if($_POST['ddata'.$desc]){
To....
for ($desc=1; $_POST['ddata'.$desc]; $desc++) {
if (isset($_POST['ddata'.$desc])) {
$ddata = $_POST['ddata'.$desc'];
} else {
continue;
}
switch($desc) {
case "1" :
$ddata = $_POST['ddata'.$desc];
$dlocatie = $_POST['dlocatie'.$desc];
break;
case "2" :
case "3" :
case "4" :
case "5" :
$ddata = $ddata.' / '.$_POST['ddata'.$desc];
$dlocatie = $dlocatie.' / '.$_POST['dlocatie'.$desc];
break;
}
}
Related
This question already has answers here:
PHP Displaying a number of asterisks depending on the number given in the input field
(4 answers)
Closed 11 months ago.
Question :
My Code :
<html\>
Enter the number of rows:
<?php
if($_POST)
{
$row = $_POST['row'];
if(!is_numeric($row))
{
echo "Make sure you enter a NUMBER";
return;
}
else
{
for($row=0;$row<=1;$row++){
for($j=0;$j<=$row;$j++){ echo "#"; } echo ""; }}}?>
The problem is it's showing only two rows
I expected as shown in the photo
$row = 10;
for($i=0;$i<=$row;$i++){
for($j=0;$j<=$i;$j++){ echo "#"; } echo "<br>"; }
You are overriding the $row variable.
Also, you don't need the else since you are returning in case the if(!is_numeric) is true;
This should do it.
if(isset($_POST['row'])) {
$rows = $_POST['row'];
if(!is_numeric($rows))
{
echo "Make sure you enter a NUMBER";
return;
}
for($row=0;$row<=$rows;$row++){
for($j=0;$j<=$row;$j++){
echo "#";
}
echo "\n";
}
}
You can make use of the PHP function str_repeat to simplify the script.
This would only take 1 loop, so you don't get confused with the variable names.
$row = 10;
$i = 1;
while ($i <= $row)
{
echo str_repeat("#", $i); echo "\n";
$i ++;
}
Working Example here.
This question already has answers here:
How to dynamically pass condition of if statement
(2 answers)
Closed 1 year ago.
This post was edited and submitted for review 1 year ago and failed to reopen the post:
Original close reason(s) were not resolved
I try to check a condition using php variable like..
if ($amount. $row['condition']. $row['amount']) {
return true;
} else {
return false;
}
but the condition always return true value ,i also echo the single variable it will show the value and also do dd($amount. $rom['condition']. $rom['amount']); it will show "500>1000" ,i remove the double qutes and manually past value in if condition it will show false with this condition, how to solve and write this condition ?
I would use a match or switch like so:
<?php
# match php 8+
$result = match ($row['condition']) {
'==' => $amount == $row['amount'],
'<' => $amount < $row['amount'],
'>' => $amount > $row['amount'],
};
# switch
switch ($row['condition']) {
case '==':
$result = $amount == $row['amount'];
break;
case '<':
$result = $amount < $row['amount'];
break;
case '>':
$result = $amount > $row['amount'];
break;
};
var_dump($result);
Try online
I've never faced such scenario, but I would imagine something like:
if ($row['condition'] == "==") {
if ($amount == $row['amount'])
return true
else
return false
}
if ($row['condition'] == ">") {
if ($amount > $row['amount'])
return true
else
return false
}
if ($row['condition'] == "<") {
if ($amount < $row['amount'])
return true
else
return false
}
Use eval()
$condition = $amount. $row['condition']. $row['amount'];
if (eval("return $condition;")) {
return true;
} else {
return false;
}
Important Note: Before using eval() make sure you have sanitized user input while inserting into database.
Docs for input sanitization : https://www.cloudways.com/blog/prevent-laravel-xss-exploits/
Im writing a page in HTML/PHP that connects to a Marina Database(boats,owners etc...) that takes a boat name chosen from a drop down list and then displays all the service that boat has had done on it.
here is my relevant code...
if(isset($_POST['form1'])){//if there was input data submitted
$form1 = $_POST['form1'];
$sql1 = 'select Status from ServiceRequest,MarinaSlip where MarinaSlip.SlipID = ServiceRequest.SlipID and BoatName = "'.$form1.'"';
$form1 = null;
$result1 = $conn->query($sql1);
$test = 0;
while ($row = mysqli_fetch_array($result1, MYSQLI_ASSOC)) {
$values1[] = array(
'Status' => $row['Status']
);
$test = 1;
}
echo '<p>Service Done:</p><ol>';
if($test = 1){
foreach($values1 as $v1){
echo '<li>'.$v1['Status'].'</li>';
}
echo '</ol>';
}else{
echo 'No service Done';
}
the issue im having is that some of the descriptions of sevice are simply Open which i do not want displayed as service done, or there is no service completed at all, which throws undefined variable: values1
how would I stop my script from adding Open to the values1 array and display a message that no work has been completed if values1 is empty?
Try this
$arr = array();
if (empty($arr))
{
echo'empty array';
}
We often use empty($array_name) to check whether it is empty or not
<?php
if(!empty($array_name))
{
//not empty
}
else
{
//empty
}
there is also another way we can double sure about is using count() function
if(count($array_name) > 0)
{
//not empty
}
else
{
//empty
}
?>
To make sure an array is empty you can use count() and empty() both. but count() is slightly slower than empty().count() returns the number of element present in an array.
$arr=array();
if(count($arr)==0){
//your code here
}
try this
if(isset($array_name) && !empty($array_name))
{
//not empty
}
You can try this-
if (empty($somelist)) {
// list is empty.
}
I often use empty($arr) to do it.
Try this instead:
if (!$values1) {
echo "No work has been completed";
} else {
//Do staffs here
}
I think what you need is to check if $values1 exists so try using isset() to do that and there is no need to use the $test var:
if(isset($values1))
foreach($values1 as $v1){
echo '<li>'.$v1['Status'].'</li>';
}
Or try to define $values1 before the while:
$values1 = array();
then check if it's not empty:
if($values1 != '')
foreach($values1 as $v1){
echo '<li>'.$v1['Status'].'</li>';
}
All you have to do is get the boolean value of
empty($array). It will return false if the array is empty.
You could use empty($varName) for multiple uses.
For more reference : http://php.net/manual/en/function.empty.php
This question already has answers here:
The 3 different equals
(5 answers)
Closed 5 years ago.
why the IF(the lastest one with else if and else) is doing all the time only first condition and only the first part ($filtry_1value[$key] = 'min_cena'), even if the condition shouldnt be true. I have another solution (less dynamic), if I will not fix this one, but I would like to know, why it is not working... I think it will be a trivial thing, but I cannot see it.
PS: I am working with laravel.
$filtry_1value = ['stat', 'lokalita', 'patro', 'min_cena', 'max_cena', 'min_uzitna_plocha', 'max_uzitna_plocha'];
foreach ($filtry_1value as $key => $filtr_1value) {
$filtr_1value = \Request::has($filtr_1value) ? \Request::get($filtr_1value) : null;
if(!empty($filtr_1value)){
if ($filtry_1value[$key] = 'min_cena' OR $filtry_1value[$key] = 'min_uzitna_plocha') {
$query->where(substr($filtry_1value[$key], 4),'>=',$filtr_1value);
}
elseif ($filtry_1value[$key] = 'max_cena' OR $filtry_1value[$key] = 'max_uzitna_plocha') {
$query->where(substr($filtry_1value[$key], 4),'<=',$filtr_1value);
}
else {
$query->where($filtry_1value[$key],'=', $filtr_1value);
}
}
}
may be-
foreach ($filtry_1value as $key => $filtr_1value) {
$filtr_1value = \Request::has($filtr_1value) ? \Request::get($filtr_1value) : null;
if(!empty($filtr_1value)){
if ($filtry_1value[$key] == 'min_cena' OR $filtry_1value[$key] == 'min_uzitna_plocha') {
$query->where(substr($filtry_1value[$key], 4),'>=',$filtr_1value);
}
elseif ($filtry_1value[$key] == 'max_cena' OR $filtry_1value[$key] == 'max_uzitna_plocha') {
$query->where(substr($filtry_1value[$key], 4),'<=',$filtr_1value);
}
else {
$query->where($filtry_1value[$key],'=', $filtr_1value);
}
}
}
You need to use the double equal sign for comparisons. == not a single =
Your if's should look like:-
if ($filtry_1value[$key] == 'min_cena' OR $filtry_1value[$key] == 'min_uzitna_plocha') {
// ...
} elseif ($filtry_1value[$key] == 'max_cena' OR $filtry_1value[$key] == 'max_uzitna_plocha') {
// ...
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Check whether $_POST-value is empty
I am using this code to validate if the passed input is not empty, but this fails when I use "white space" in the input. It does pass the empty() check.
if (empty($_POST['r_user'])) {
$data['error'] = 'Please pick a username to continue.';
$data['errorID'] = 'r_user';
}
What is the proper method to check an empty string in PHP?
You need to use trim function before checking the variable.
$trimUser= trim ($_POST['r_user']);
now execute the empty method.
as per PHP documentation suggestion, your code would become:
if (trim($_POST['r_user']) == false) {
$data['error'] = 'Please pick a username to continue.';
$data['errorID'] = 'r_user';
}
you can trim() removes white space from the beginning and end of a string
working example
$test = " ";
if(trim($test)){
if (empty($test))
echo "true";
else
echo "false";
}
live : check this on codepad
You may use :
$var = '';
if (array_key_exists('r_user', $_POST)) {
$var = trim($_POST['r_user']);
}
if (empty($var)) {
// do some stuffs
}
instead.
You can use trim nicely here, it removes whitespace front and back:
if (empty(trim($_POST['r_user']))) { // Incorrect!
Edit, wow, learned a new thing today.
This will however work:
$var=trim($_POST['r_user']);
if (empty($var)) {
Working Example:
<?php
$var=' ';
$var=trim($var);
if(empty($var))
echo "Yay";
else
echo "Nay!";
?>
Output:
Yay
if ( empty( trim( $_POST['r_user'] ))) {
// wrong! gives an error - learned something new :)
// the right way should be :
$myvar = trim( $_POST['r_user'] );
if ( empty( $myvar )) {
or
if ( trim( $_POST['r_user'] ) != '' ) {
if(isset($_POST['r_user'])){
// ur code
}