php for loop: error message if condition not met - php

My foreach loop:
$empty = "You cannot decommission this truck. It is in use."
$msg = "";
foreach ($trucks_to_remove as $truck_id) {
$truck_id = trim($truck_id);
if (strlen($truck_id)) {
$msg .= decom_truck(
$db,
$depot_id,
$truck_id
);
}
else
{
echo $empty;
}
}
echo $msg;
If the condition is not met, it means the sql cursor that preceded this foreach loop did not return a result for this truck_id (meaning it is in use), I just want a simple message sent to the page to alert the user.
It does not have to be a pop-up or the like. Where would I put my write or print statement? I assume I'd use an else clause but when I add an else inside the foreach loop (see above), I get nothing printed to the page. I have also tried the following:
else if (strlen($truck_id)) == 0
{
echo $empty;
}
I am very new to php.

$arr1 = array();
if(!$arr1)
{
echo 'arr1 is emty<br/>';
$arr2 = array(1, 2);
if($arr2)
echo 'arr2 has data';
exit();
}

Related

PHP Echo Appearing Twice

I am trying to show an echo when a user improperly enters their license key, though, for some reason, the message appears twice.
$invalidkey = '<!DOCTYPE HTML>
<html>
<body>
<center>
<div class="container2"
<h1>Your Product Key is Invalid!</h1>
</div>
</center>
</body>
</html>
';
if ($resulto->num_rows > 0)
{
while($row = $resulto->fetch_assoc())
{
$user_group = $row["LicenseKey"];
$days = $row["Count"];
// Key is valid
if ($user_group == $key)
{
$keyvalidated = true;
echo $user_group;
echo $key;
}
// Key is invalid
else if ($usergroup !== $key)
{
echo $invalidkey;
$keyvalidated = false;
}
}
}
Here is an image of the error actually appearing:
My guess is that for whatever reason there are actually two records in the result set. The best fix would be to find a way to run the right query, which just returns a single record for a single user. As a quick fix, perhaps just check the first record:
if ($resulto->num_rows > 0) {
$row = $resulto->fetch_assoc();
$user_group = $row["LicenseKey"];
$days = $row["Count"];
// Key is valid
if ($user_group == $key) {
$keyvalidated = true;
echo $user_group;
echo $key;
}
// Key is invalid
else if ($usergroup !== $key) {
echo $invalidkey;
$keyvalidated = false;
}
}
Again, you need to find out why the result set has two, or more than one, records.
Please try adding a break since there could be more than one iteration (or you wouldn't need a loop):
// Key is invalid
else if ($usergroup !== $key)
{
echo $invalidkey;
$keyvalidated = false;
break;
}
The reason why it's showing 2 times is because query is fetching 2 results. So you need to limit query to just 1, just read the first record, or break the loop after 1st iteration.
while($row = $resulto->fetch_assoc())
{
$user_group = $row["LicenseKey"];
$days = $row["Count"];
// Key is valid
if ($user_group == $key)
{
$keyvalidated = true;
echo $user_group;
echo $key;
}
// Key is invalid
else if ($usergroup !== $key)
{
echo $invalidkey;
$keyvalidated = false;
}
break;
}

How do you make sure an array is empty in PHP?

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

PHP- How to solve else in nested foreach loop

This my code syntax all conditions are working but last else is not working. I found solution in there https://stackoverflow.com/a/5930255/7688968 and I am used break 2 but still not working. How can I solve that?
<?php
$rows = $wpdb->get_results( "SELECT * FROM test WHERE approve_status = '1'" );
if($rowcount>0)
{
foreach ($rows as $row)
{
if ( is_user_logged_in() )
{
echo 'I am user';
$demo = $wpdb->get_results("SELECT * FROM abc WHERE user_mail = '$curentmail'");
foreach($demo as $demos)
{
if(!empty($demos->id)){
echo 'I am IF';
break 2;
}
else{
echo 'I am last ELSE';
}
}
}
else{
echo 'I am guest user';
}
}
}
You are doing the else in the wrong place, it should be done instead of the foreach...
$demo = $wpdb->get_results("SELECT * FROM abc WHERE user_mail = '$curentmail'");
if(!empty($demo)){
foreach($demo as $demos)
{
echo 'I am IF';
}
}
else{
echo 'I am last ELSE';
}
So the logic is that if no records are returned then display your message.
Because the break doesn't break if's. You need to break the foreachs only once, so it's just break;
That else actually doesn't run, because the if is not false. If it uses break in the ifs, else won't run at all. The innermost else runs only, if the very first id of $demos is empty. The second only when if the user is not logged in. These don't relate too much for the foreach cycles.
Move whole foreach block in the function and return from it when needed. For example:
if($rowcount>0)
{
doStuff($rows);
}
function doStuff($rows) {
global $wpdb, $curentmail;
foreach ($rows as $row)
{
if ( is_user_logged_in() )
{
echo 'I am user';
$demo = $wpdb->get_results("SELECT * FROM abc WHERE user_mail = '$curentmail'");
foreach($demo as $demos)
{
if(!empty($demos->id)){
echo 'I am IF';
return;
}
else{
echo 'I am last ELSE';
}
}
}
else{
echo 'I am guest user';
}
}
}

How can I place text that relates to a foreach function, outside the loop?

I'm really unsure how to describe this, so please forgive me.
Basically, I'm reading from an XML, and then generating an IF statement that checks all records in the XML and if a condition matches, details about that record is displayed.
What I want to add, is a similar function but in reverse, but outside the foreach loop, so it's only displayed once.
foreach($xml as $Reader) { $items[] = $Reader; }
$items= array_filter($items, function($Reader) use ($exclude) {
if($Reader->Picture == 'None' || in_array($Reader->Pin, $exclude)) {
return false;
}
return true;
});
usort ($items, function($a, $b) {
return strcmp($a->Status,$b->Status);
});
foreach($items as $Reader) {
if($Reader->Status == 'Available' && !in_array($Reader->Pin, $exclude)) {
echo "<a href='/details?Pin=".$Reader->Pin."'>".$Reader->Name ." (".$Reader->Pin.")</a> is available! ... ";
}
}
if (!$items) { echo "Please check back in a moment when our readers will be available!"; }
So, in the XML file each Reader has a Status that can be one of three values: Available, Busy or Logged Off.
So what I'm doing, is for each record in the XML, checking if the Reader status is available.. and if so, echo the above line.
But I want to add in, that if NONE of the readers show as 'Available' to echo a single line that says 'Please check back in a moment'.
With the code above, ifthere are four readers online, but they're all busy.. nothing is displayed.
Any ideas?
Just use a simple boolean value
$noneAvailable = true;
foreach($items as $Reader) {
if($Reader->Status == 'Available' && !in_array($Reader->Pin, $exclude)) {
echo "<a href='/details?Pin=".$Reader->Pin."'>".$Reader->Name ." (".$Reader->Pin.")</a> is available! ... ";
$noneAvailable = false;
}
}
if ($noneAvailable) {
echo "Please check back in a moment";
}
I managed to take the answer given above, and combine it with XPath to just filter the records in the XML based on the status given using xPath.
include TEMPLATEPATH."/extras/get-readers.php";
$readers = $xml->xpath('/ReaderDetails/Reader[Status="Available"]');
$gotOps = false;
foreach ($readers as $Reader)
{
echo "<a href='/details?Pin=".$Reader->Pin."'>".$Reader->Name ." (".$Reader->Pin.")</a> is available! ... ";
$gotOps = true;
}
if ($gotOps!=true)
{
echo 'Please check back in a moment when our readers will be available!';
}

showing success messages in php

I would like to show success message if execute is successful. The below code doesn't show the message just deletes it. what am I missing?
$errors = array();
$delete = $mydb->prepare("update messages set deleted = 'yes' where to_user = ? and id = ? ");
$delete->bind_param('ss', $username->username, $id);
foreach ($_POST['id'] as $id) {
$delete->execute();
}
$errors[] = "Message Deleted.";
}
<div><?php
if ($delete->execute()) { echo $errors;}
?>
</div>
$errors seems to be an array so you will have to loop through it to echo errors which can be done by
foreach($errors as $value){
echo $value;
}
, but from the above code it seems you have only one value in array so you can use
echo $errors[0];
Also note you may need to be change this
if ($delete->execute()) { echo $errors;}
to
<?php
if (count($errors)>0) { echo $errors;}
?>
Thanks
Variable $errors is An array not a string and you can NOT echo array variable,
you have to use foreach($errors AS $v) echo $v;

Categories