PHP verify if every $array[$key] is not empty - php

So, i have this code that seems to be doing the mechanical work correctly, avoiding to write on tables if one or more fields from a form are left empty, but the echos and messages aren't working as they supposed to:
SOLUTION TO THE PROBLEM:
I don't believe this will be useful to anyone, but just for the record, the solution is simple:
$campos = array('nome','morada','email','telemovel','codigopostal','vat');
foreach ($campos as $key => $campo) {
$campos[$key] = $_GET[$campo];
if(!isset($_GET[$campo])|| empty($_GET[$campo])){
header("Location: ../index.php?erro=".$campo);
$verifica=FALSE;
die();
}else{
$verifica=TRUE;
}
}
This will give me some problems, not what i really wanted but solves the logical problems i was having. Thanks to you all guys.
$campos = array('nome','morada','email','telemovel','codigopostal','vat');
foreach ($campos as $key => $campo) {
$campos[$key] = ($_GET[$campo]);
while(list($key, $campo)= each($campos))
if(!isset($_GET[$campo])|| $_GET[$campo]==""){
echo("não preencheu um dos campos");
$verifica = FALSE;
die();
}else{
echo $_GET[$campo]." \r\n";}
$verifica = TRUE;
}
if($verifica==TRUE){
some irrelevant code.
}
As i said, the code itself is working flawlessly, BUT if i only left 2 empty fields on the form, the echo $_GET[$campo] will be working even though the variable $verifica will be set as FALSE
AN HINT:
One of the fields is making the code to fail, is the second one, so, if i do this:
../phcexport.php?nome=myname&morada=&codigopostal=postcode&email=#.com&vat=12312­3&telemovel=00800
And ignore the second value from the array, the code will work like a charm, i can try as many combinations as i can as long as i left the second field empty, it will work properly, giving me the error "some field is empty", in this case i know it is, the "morada" is empty, and if i fill it in the code says "its ok, all filled in" BUT the "morada" should be the last to be filled so the code works. Funny... (I'm sorry about all the text to describe the problem, i'm Portuguese)
EDIT2: For the rest of the code i need to use $campos[$key], so attribute a key to the arrays is essencial.

The problem is that you reset $verifica in the else. So regardless if you set it once to FALSE, the last foreach iteration will determine the outcome. But you can "simplify" the whole approach to:
$verify = array_search(0, array_map("strlen", $campos)) === false;
This simply checks for the string length of each array entry. If none of them is 0, then the expression will return true for $verify;

instead of doing $_GET[$campo]=="", you can maybe use the empty function :
empty($_GET[$campo])
This should address all problems related to different data types.
Your also maybe running in a problem because you're using a variable named $campo in two different loops, try changing the variable name in the while loop to see if it works better.

Check the exact value of $campo that is causing the incorrect behaviour, then consult this table to make sure you are using the right kind of comparison
http://www.php.net/manual/en/types.comparisons.php#types.comparisions-loose

try following solution, empty fields can not pass the test
<?php
$campos = array('nome', 'morada', 'email', 'telemovel', 'codigopostal', 'vat');
$verifica = TRUE;
foreach ($campos as $campo) {
if (!isset($_GET[$campo]) || empty($_GET[$campo])) {
echo "não preencheu um dos campos" ;
$verifica = FALSE;
break;
} else {
echo $_GET[$campo] ."\r\n";
}
}
if ($verifica == TRUE) {
// some irrelevant code.
} else {
die();
}

Related

array_push does not add value in case of used inside of foreach > if

I'm currently working on a website for my project, but for some reason when everything is as it has to be ( session is started, session variable is defined ), then only array_push() function doesn't add the value to session variable, when I move array_push() out of if, foreach and if (if contains foreach and foreach contains another if), it works fine, I already tried to put it to first if, then to foreach but it didn't help. So it works only when it is out of that code (When it is not in that if, which contains foreach, which contains another if). Please try to understand, my English is not well.
What do I have to do to fix it?
if(isset($_GET["setLang"])) {
foreach ($languages as $item) {
if($item === $_GET["setLang"]) {
$_SESSION["selLang"] = $item;
array_push($_SESSION["sessionMessage"], "Language changed successfully!");
header("location: index.php?path=/");
exit();
}
}
}
Since the code work correctly out of the if statement , it's cleary evident that the condition cause the problem
$item === $_GET["setLang"]
Using triple = will check value and type . So may be the type of each ones is different than other .
Replace it with :
$item == $_GET["setLang"] // only use two =

PHP compare subsequent array element to previous

So i'm having trouble getting a bit of code to work. Essentially what I want to do is:
in a foreach loop, if a given array value is set, compare that existing value to the current loop value, then set the existing value = current value (for the iteration) if the existing value is already greater than current val. Here is the code i'm working with:
if ($usedebayxml->ack == 'Success') {
foreach($usedebayxml->searchResult->item as $key => $value) {
if(isset($newarray[1]['TotalCost'])) {
if($newarray[1]['TotalCost'] > ((integer)$value->shippingInfo->shippingServiceCost + (integer)$value->sellingStatus->currentPrice)) {
$newarray[1]['Title'] = (string)$value->title ;
$newarray[1]['ShippingCost'] = (integer)$value->shippingInfo->shippingServiceCost;
$newarray[1]['Price'] = (integer)$value->sellingStatus->currentPrice;
$newarray[1]['Condition'] = 'New';
$newarray[1]['TotalCost'] = (integer)$value->shippingInfo->shippingServiceCost + (integer)$value->sellingStatus->currentPrice;
}
}
else
$newarray[1]['Title'] = (string)$value->title;
$newarray[1]['ShippingCost'] = (integer)$value->shippingInfo->shippingServiceCost;
$newarray[1]['Price'] = (integer)$value->sellingStatus->currentPrice;
$newarray[1]['Condition'] = 'Used';
$newarray[1]['TotalCost'] = (integer)$value->shippingInfo->shippingServiceCost + (integer)$value->sellingStatus->currentPrice;
}
}
With this code, what is returned is ultimately the values in the LAST key object in the xml file (im using simpleXML if that helps). In other words, i don't think the first if block (if isset) is being entered into, and the values are being set to whatever the values are for the current iteration. Can anyone see any flaw in my logic here? I've been stumped on this one for a while.
I am a supreme idiot. The logic here is fine, i was just missing a { for the opening else block. dur! After adding this, this bit of code works as intended :)
I'm surprised though that i wasn't throwing any errors without having this....I think that was probably throwing me off in determining why it wasn't working originally.

Trying to remove an item from an array but it wont work

I dont really understand why this is not working, I am being returned to the correct header but the item is still in the array!
Here is the remove from array code:
<?php
session_start();
if ( !isset($_SESSION['username']) )
{
header("Location:loginform.php");
exit();
}
foreach ($_SESSION['list'] as $key => $disk)
{
if (($_SESSION['list'][$key]['bookisbn']) - ($_GET['bookisbn'])== 0)
{
unset($_SESSION['list'][$key]);
break;
}
}
header("Location: ".$_GET['location']);
exit();
?>
Thank you for any help you can offer
This is only a guess but the problem may lie in the fact that
$_GET['bookisbn']
is being treated as a string. Therefore if you cast it to an int
the if statement will return true removing the item from the
array.
Introduce this code:
// Casting the ISBN to an integer here
$bookISBN = (int) $_GET['bookisbn'];
if( ($_SESSION['list'][$key]['bookisbn'] - $bookISBN) == 0 ) {
// Unset item
}
I would listen to Artragis, but also try this:
You have parenthesis around each of the variables, but it's really the subtraction that has to equal zero. So, instead of:
if (($_SESSION['list'][$key]['bookisbn']) - ($_GET['bookisbn'])== 0)
{
unset($_SESSION['list'][$key]);
break;
}
Try:
if (($_SESSION['list'][$key]['bookisbn'] - $_GET['bookisbn']) == 0)
{
unset($_SESSION['list'][$key]);
break;
}
EDIT:
I would also cast both the Session and the GET variables as INTs, like one of the other posters mentioned, as well.
Try session_write_close() before the header. Perhaps is not saving.
You can also do this:
$mydata = $_SESSION['list'] ;
//do something with $mydata
$_SESSION['list'] = $mydata;
It will result in easier to read code, if you have other type of error, with this way you will not make the same mistake again.
You need to debug and test if line with unset is reachable.
You need to debug means you need to verify every program's step and every variable.
You need to test if line with unset is reachable means you have to echo something at the point of unset:
foreach ($_SESSION['list'] as $key => $disk)
{
var_dump("---\n",$_SESSION['list'][$key]['bookisbn'],$_GET['bookisbn']);
var_dump($_SESSION['list'][$key]['bookisbn'] - $_GET['bookisbn']);
var_dump($_SESSION['list'][$key]['bookisbn'] - $_GET['bookisbn'] == 0);
if ($_SESSION['list'][$key]['bookisbn'] - $_GET['bookisbn'] == 0)
{
unset($_SESSION['list'][$key]);
var_dump($_SESSION['list']);
break;
}
}
//comment out header to prevent moving out of page
#header("Location: ".$_GET['location']);
exit();
run this code and see if any of the values are wrong or unexpected.

PHP: make a 'fake'/custom statement in while

I have this while loop.
while($show = $queryActivities->fetch()){ echo $show["name"]."<br>"; }
This takes data from the query and outputs the names..
Now is it possible to make a custom/fake data? I would like to make one if theres no data/statement in the $queryActivities then it should make a custom one called "name" with value "Nothing here.."
Is this possible? Can you do that?
I know I can do if($queryActivities->rowCount == 0){ echo "Nothing here" ; }
But I more thought of creating a custom data, so it runs the while loop, with the custom data, that only gets made if theres nothing in $queryActivities.
Something like..:
if($queryActivities->rowCount == 0){
# ..MAKE CUSTOM DATA..
# ..SOMETHING LIKE THIS MAYBE: ..
# $queryActivities = MAKE ARRAY WITH name => 'Nothing here'.. (just a thought)
}
while ($show = $queryActivities->fetch()){
echo $show["name"]."<br>";
}
Something like this, just what I imagine, although I dont know really how.
Thank you
Retrieve your data to an array, and then print it out. In between these two steps, you can modify it as desired.
This is more orderly, anyhow. I don't like retrieving from the DB and displaying in one step
You could either have an if/else that checks if the array is empty and prints a default message, or creates a default entry with a 'name' property that then is displayed with the same output loop as normal data. I'd prefer the first, but we'll do the second style since that's what you asked about.
Here's one simple solution.
$activities=array();
while($show = $queryActivities->fetch()){ $activities[]=$show; }
if(empty($activities)){ $activities=array(array('name'=>'None Found')); }
foreach($activities as $activity){
echo $activity['name']."<br>";
}
I think just using an if/else is a better solution. Depending on your output style, though, this might involve more code repetition.
$activities=array();
while($show = $queryActivities->fetch()){ $activities[]=$show; }
if(empty($activities)){
echo "None found <br>";
}
else{
foreach($activities as $activity){
echo $activity['name']."<br>";
}
}

PHP - Is there a way to verify all values in an array

Using PHP..
Here is what I have.. I'm gonna explain the whole thing and maybe someone can help me with the logic and maybe point me in the right direction.
I have a mail system I am working on. In the cc part, I am allowing the user to seperate the values by a semicolon, like so: 1;2;3;4...
When these values are passed to my function, I am using explode to get them into an array. What I want to do is some checking first. I want to firstly make certain that the format is correct and that every value is correctly seperated. If not, I should show an error. Once this is done, I want to make certain that every number is actually valid. I can query the database, put the reslts into an array and was thinking to use the in_array() function to verify this but I'm not certain that it will work. Can someone please help me out with the best way to handle this?
Thanks.
EDIT:
What is the best way to detect a bogus value in the CSV list of values?
In order to verify that each number was correct seperated, you want to check that there is no whitespace in the answer. So something like this should work:
$text = trim($id);
if(strpos(" ", $id) !== false)
{
//error
}
Next, to check for the values, it is very simple
if(!in_array($id, $database_ids))
{
// error
}
Finally, if you are only using numeric values, check that the id is numeric
if(!is_numeric($id))
{
//error
}
To combine, wrap it into an array
foreach($exploded_array as $key => $id)
{
$id = trim(id);
if(!is_numeric($id))
{
//error
}
if(strpos(" ", $id) !== false)
{
//error
}
if(!in_array($id, $database_ids))
{
// error
}
}
I hope the code was pretty self explanatory where it got the variables, but if you need me to explain more, feel free to ask.
You are looking for something like:
foreach ($array as $value) {
//do checking here
}
array_filter could be an option.
As whichdan suggested, here is an implementation that relies on array_filter():
<?php
function checkValue($value)
{
$id = trim(id);
if(!is_numeric($id))
{
return false;
}
if(strpos(" ", $id) !== false)
{
return false;
}
if(!in_array($id, $database_ids))
{
return false;
}
return true;
}
$values = '1;2;3;4';
$values_extracted = explode(';', $values);
if(count($values) == count(array_filter($values_extracted), 'checkValue'))
{
// Input was successfully validated
}
?>

Categories