First of all, I know this question already exists and already has answers, but I would like to stress in which way my question is different. I have code like this:
$ognjen=array();
foreach($_POST as $key=>$value){
if($key!='prenos'&& $key!='submit'){
if (strrpos($key, '1', -1)){
if(!empty($_POST[$key])){
$uslov=true;//kontrolna promjenljiva
}else{
$uslov=false;
}
if($uslov==true){
$ognjen[]=$value;
}else{
$_SESSION['message']='You must fill out all fields';
unset($_SESSION['message']);
}
}//ovdje ide elseif
}
}
This code doesn't do what's expected.What I want to achieve is if all values of $_POST are set to put them in $ognjen array,if even one misses, none of them should become part of $ognjen array, but all that inside this foreach loop, because there are some other checkings that need to fulfill. And while searching for answers I couldn't find any that fits to my situation. Please help, I feel that this is pretty simple task to do, but I don't know way to do it.
<?php
function is_blank($data)
{
$error_message="";
foreach ($data as $key => $value)
{
if($value=="" or $value==null)
{
$error_message.=$key.",";
}
}
if($error_message!="")
{
$error_message=substr($error_message, 0,-1);
return $error_message." is cannot be null or empty.";
}
else
{
return "";
}
}
echo is_blank($_POST);
Related
I need to check the words received from the database with the user's entered word and if there is a match, then output its value from the database, and if not, then output what the user entered.
The code below works fine if there is a match.
function d_typeplace_morf($d_typeplace)
{
global $wpdb;
$typeplace_results = $wpdb->get_results('SELECT vozmozhnyi_variant_mesta, ego_slovoforma_v_predlozhnom_padezhe FROM dEzpra_jet_cct_tip_mest_obrabotki');
if ($typeplace_results) {
foreach ($typeplace_results as $typeplace_result) {
$d_typeplace_raw = mb_strtolower($typeplace_result->vozmozhnyi_variant_mesta);
$d_typeplace_morf = mb_strtolower($typeplace_result->ego_slovoforma_v_predlozhnom_padezhe);
$d_typeplace = mb_strtolower($d_typeplace);
if (stripos($d_typeplace, $d_typeplace_raw) !== false) {
echo $d_typeplace_morf;
}
}
}
}
I'm an amateur in PHP, just learning. And I can't figure out how to output $d_typeplace if no match is found.
I tried to add
else {
echo $d_typeplace;
}
, but I get an array of words from the user entered.
I will be grateful for any help. Also for any suggestions for improving this code.
---Addition---
I apologize for my English. This is a problem in the Russian language, I need to take into account the morphology. To do this, the database has a list of words and their analog, for example, X = Y. I get these words and compare what the user entered. If he entered X, then we output Y. If he led Z, which is not in the database, then we output Z.
Thus, we check $d_typeplace with $d_typeplace_raw and if there is a match, we output $d_typeplace_morf, which is equal to $d_typeplace_raw. And if not, then $d_typeplace (it contains the value that the user entered).
Oh, I'm sorry, I understand myself that I'm explaining stupidly)
I cannot quite understand what you are asking: you need to output the string entered by the user, but you can only print an array?
If this is the case, I think you parsed the string before, in order to therefore you need to do join again the values contained in the array.
Try with:
else {
echo implode(" ", $d_typeplace);
}
--- EDITED ---
Try with:
function d_typeplace_morf($d_typeplace)
{
global $wpdb;
$typeplace_results = $wpdb->get_results('SELECT vozmozhnyi_variant_mesta, ego_slovoforma_v_predlozhnom_padezhe FROM dEzpra_jet_cct_tip_mest_obrabotki');
if ($typeplace_results) {
$found = false;
foreach ($typeplace_results as $typeplace_result) {
$d_typeplace_raw = mb_strtolower($typeplace_result->vozmozhnyi_variant_mesta);
$d_typeplace_morf = mb_strtolower($typeplace_result->ego_slovoforma_v_predlozhnom_padezhe);
$d_typeplace = mb_strtolower($d_typeplace);
if (stripos($d_typeplace, $d_typeplace_raw) !== false) {
echo $d_typeplace_morf;
$found = true;
break;
}
}
if (!$found) {
echo $d_typeplace;
}
}
}
But I think it would be more efficient, if you implemented the second code snippet written by #Luke.T
I'm presuming you were trying to add the else like this?
function d_typeplace_morf($d_typeplace)
{
global $wpdb;
$typeplace_results = $wpdb->get_results('SELECT vozmozhnyi_variant_mesta, ego_slovoforma_v_predlozhnom_padezhe FROM dEzpra_jet_cct_tip_mest_obrabotki');
if ($typeplace_results) {
foreach ($typeplace_results as $typeplace_result) {
$d_typeplace_raw = mb_strtolower($typeplace_result->vozmozhnyi_variant_mesta);
$d_typeplace_morf = mb_strtolower($typeplace_result->ego_slovoforma_v_predlozhnom_padezhe);
$d_typeplace = mb_strtolower($d_typeplace);
if (stripos($d_typeplace, $d_typeplace_raw) !== false) {
echo $d_typeplace_morf;
} else {
echo $d_typeplace;
}
}
}
}
Which was outputting an array because the for loop was continuing, if you add a break like so...
echo $d_typeplace;
break;
It should stop outputting an array. Depending on your use case you could however perform similar functionality directly in your sql query using LIKE ...
function d_typeplace_morf($d_typeplace)
{
global $wpdb;
$typeplace_results = $wpdb->get_results('
SELECT ego_slovoforma_v_predlozhnom_padezhe
FROM dEzpra_jet_cct_tip_mest_obrabotki
WHERE vozmozhnyi_variant_mesta LIKE %' . $d_typeplace . '%');
if ($typeplace_results) {
//Echo result
} else {
echo $d_typeplace;
}
}
Hello I have a simple script
This is my script, and try this script
<?php
$user_id = $_REQUEST['user_id'];
$pid = $_REQUEST['pid'];
$nopr = $_REQUEST['nopr'];
$tglpr = $_REQUEST['tglpr'];
$uraianpr = $_REQUEST['uraianpr'];
$jenispr = $_REQUEST['jenispr'];
$nilaipr = $_REQUEST['nilaipr'];
$costproject = $_REQUEST['costproject'];
$remarkpr = $_REQUEST['remarkpr'];
$tmpattachid = $_REQUEST['tmpattachid'];
if ($user_id==NULL)
{
$error "User Id Not Complete";
}
else if ($pid==NULL)
{
$error= "PID Not Complete";
}
echo $error;
?>
I want if $user_id or other variables is empty/null
i confused when other variable have empty/null data
i must typing code many if statement :(
example : 5 variables ($pid,$nopr,$tglpr,$jenispr,$costproject) is empty/null
this show error like this
PID Not Complete
NoPR Not Complete
Tgl Pr Not Complete
Jenis Pr Not Complete
Cost Project Not Complete
Help Me, Thank's.
I won't give you the full answer, as stated in comments, this is a basic basic concept you need to learn, but I will show you the template.
You want to use a FOREACH loop to check each value in the array. See http://php.net/manual/en/control-structures.foreach.php
And Set it out like this:
foreach($_REQUEST as $key=>$row){
if (is_null($row) || empty($row)){
$errorText .= "You have no data in your ".$key."<br>";
}
}
unset($key,$row);
Then you can output the $errorText value telling people which rows should be fixed. Easy.
Loop through the $_REQUEST and find the empty or null key.
CODE :
foreach ($_REQUEST as $key => $value) {
if(trim($value) ==='' || is_null($value))
{
echo $key . " is not complete" . "<br/>";
}
}
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!';
}
I'm trying to echo content inside a foreach once. At the moment, when a form is filled by the user, the message is displayed for every record skipped. If there are 35 records skipped, I will get 35 messages, because of the foreach. I want to avoid this, and be able to display only one echo for the entire results page. How can I do this? I suppose I may have to do this outside the foreach, but I have no clue how to take it out of the foreach.
foreach($allcourses as $course)
{
if(Auth::LoggedIn())
{
if(Auth::$userinfo->rank == 'Student')
{
if($course->aircraft == '1')
{
echo '<div class="msg-red">Some lessons could not be found, because you may not be entitled to view/book them at this stage of your course.</div><br/>';
continue;
}
if($course->aircraft == '2')
{
echo '<div class="msg-red">Some lessons could not be found, because you may not be entitled to view/book them at this stage of your course.</div><br/>';
continue;
}
}
}
}
Assuming you must maintain the structure of that object, you could just have a boolean update if $course->aircraft == 1 then echo accordingly:
$found = false;
foreach($allcourses as $course)
{
if(Auth::LoggedIn())
{
if(Auth::$userinfo->rank == 'Student')
{
if($course->aircraft == '1')
{
$found = true;
}
}
}
}
if($found)
{
echo '<div class="msg-red">Some lessons could not be found, because you may not be entitled to view/book them at this stage of your course.</div><br/>';
}
You can set a simple flag variable in this case.
$warningEmitted = false;
Then, in your loop prior to emitting a warning:
if(!$warningEmitted) {
// echo warning here.
$warningEmitted = true;
}
The best option would probably be to set your message as a variable, then echo the variable after the foreach is finished.
foreach($allcourses as $course)
{
if(Auth::LoggedIn())
{
if(Auth::$userinfo->rank == 'Student')
{
if($course->aircraft == '1')
{
$message = '<div class="msg-red">Some lessons could not be found, because you may not be entitled to view/book them at this stage of your course.</div><br/>';
continue;
}
}
}
}
if(isset($message))
{
echo $message;
}
Outside the loop assume $count=1;
Inside the loop, you can put an if statement.
if($count==1) { $count++; echo "Whatever";}
Hope this helps.
Just use a boolean variable which you set to false initially, and the set it to true in the loop if you get a match.
Then you can check the boolean after the loop has finished to decide if you need to display the message or not.
Create additional variable in which you will store information whether the message was already displayed or not. When you display it, set the var to true.
Assuming I understand you correctly, I think you want to use 'break' to stop looping as soon as a problem is found.
if (Auth::LoggedIn() && Auth::$userinfo->rank == 'Student') {
foreach ($allcourses as $course) {
if ($course->aircraft == '1') {
echo '<div class="msg-red">Some lessons could not be found, because you may not be entitled to view/book them at this stage of your course.</div><br/>';
break;
}
if ($course->aircraft == '2') {
echo '<div class="msg-red">Some lessons could not be found, because you may not be entitled to view/book them at this stage of your course.</div><br/>';
break;
}
}
}
Above I've also moved the "if logged in" conditional to be outside the loop (so it's only checked once).
Something to consider:
A more user friendly approach might to add each error into an array - instead of using echo & breaking out - and then loop through that error array at the end, showing with more information about the error so they can be corrected all at once by the end user (depending on how your form works, of course).
I know there must be a nicer way to do this, but whenever I search "&&" i don't get good enough results...
<?php
if (empty($row[ContactName]) && empty($row[ContactEmail]) && empty($row[ContactPhone]) && empty($row[Website])){
echo "Not Provided";
}
else{
...do stuff...
}
?>
Thanks!
What is wrong with the original code?
<?php
if (empty($row[ContactName])
&& empty($row[ContactEmail])
&& empty($row[ContactPhone])
&& empty($row[Website]))
{
echo "Not Provided";
}
else{
...do stuff...
}
?>
Looks like fine code to me...
<?php
$i=1;
$ar=array('ContactName','ContactEmail','ContactPhone','Website')
foreach($ar as $a)
if (empty($row[$a]))
{
$i=0;
break; //to make code fast
}
if($i) //do stuff
else echo 'not provided';
?>
or if you really want to make your code extra small then change your column name in database
From To
ContactName Col1
ContactEmail Col2
ContactPhone Col3
Website Col4
and then do
<?php
$i=1;
for($a=1;$a<5;$a++)
if (empty($row['Col'.$a]))
{
$i=0;
break;
}
if($i)//do stuff
else echo 'Not Provided';
?>
However it is not good to rename column as it will make your db somewhat less understandable.
As php functions have a lot of inconsistency, It's always a good idea using a library to make it more consistent.
put this function in that library:
function empty()
{
foreach(func_get_args() as $arg) if (empty($arg)) return false;
return true;
}
usage:
if (empty($row[ContactName], $row[ContactEmail], $row[ContactPhone], $row[Website])) {
echo "Not Provided";
}
you could make it as short as this if compactness was more important than readability :)
$required = array('ContactName', 'ContactEmail', 'ContactPhone', 'Website');
$ra = array_filter(array_intersect_key($row,array_flip($required)));
if(empty($ra)){
echo "Not Provided";
}
else{
//....
}
you can't put array_filter inside empty() or you get "Fatal error: Can't use function return value in write context"
1) array flip is turning your $required values into keys
2) array_intersect_key throws away any $row keys not found in $required
3) array_filter throws away any empty values
leaving you with a zero length array, which is empty. No need to worry about array lengths or loops
<?php
$flag = 1;
if (empty($row[ContactName])){
$flag = 0;
}
if (empty($row[ContactEmail])){
$flag = 0;
}
if (empty($row[ContactPhone])){
$flag = 0;
}
if (empty($row[Website])){
$flag = 0;
}
if($flag == 0){
echo "Not Provided";
}else{
//do stuff
}
?>
OR
$flag = 1;
$i=0;
$mustarray = array('ContactName','ContactName','ContactName','ContactName'); //or any number of fields that you want as mandatory
foreach($yourresult as $row){
if(empty($row[$mustarray [$i]])){
$flag = 0;
}
$i++;
}
if($flag == 0){
echo "Not Provided";
}else{
//do stuff
}
Do not play with making arrays and stuff just to make code look nicer.
As Tommy pointed
<?php
if (empty($row[ContactName])
&& empty($row[ContactEmail])
&& empty($row[ContactPhone])
&& empty($row[Website]))
{
echo "Not Provided";
}
else{
...do stuff...
}
?>
this code is nice, just need proper formatting like he pointed.
Making arrays and then launching loop will decrease performance
<?php
$i=1;
for($a=1;$a<5;$a++)
if (empty($row['Col'.$a]))
{
$i=0;
break;
}
if($i)//do stuff
?>
this might look small, nice and "pro", but has more operations to give same results as a simple if instruction.
Not saying that it cant be done faster, i don't know php well, just remember about code executing speed.