Hi lets say I've got this array:
$check_post = array(
$_POST["a_post"],
$_POST["b_post"],
$_POST["c_post"],
$_POST["d_post"],
$_POST["e_post"],
$_POST["f_post"],
$_POST["g_post"],
$_POST["h_post"],
$_POST["i_post"]
);
I want to check whether any elements of this array are repeated, so the best I got is this:
if (count(array_unique($check_post)) < count($check_post))
echo "Duplicate";
else
echo "NO Duplicate";
Which works fine except for the fact that if more that one textarea is left blank (which is allowed) it gives me FALSE.
What I want is to NOT consider the empty values of the array for the (count(array_unique())
BTW I have tried with empty() and with array_values($check_post) but I cant get around it.
Thanks in advance!! please ask for any needed clarification.
To remove all the empty values from the comparison you can add array_diff():
if (count(array_unique(array_diff($check_post,array("")))) < count(array_diff($check_post,array(""))))
Well the way you have it is fine, though as you say, you have a need to remove the empty entries first.
$non_empty_check_post = array_filter($check_post, create_function('$item', 'return !empty($item);');
if (count(array_unique($non_empty_check_post)) < count($non_empty_check_post)) {
echo "Duplicate";
} else {
echo "NO Duplicate";
}
Filter out the blanks from your array:
function no_blanks($val) {
// Do not use empty() here if you don't consider the string "0" as blank
return trim($val) !== '';
}
$check_post = array_filter($check_post, 'no_blanks');
if (count(array_unique($check_post)) < count($check_post))
echo "Duplicate";
else
echo "NO Duplicate";
if (count(array_unique(array_filter(function(x) {return !empty(x)}, $check_post)) < count($check_post))
echo "Duplicate";
else
echo "NO Duplicate";
Related
I want to check if array is empty or not, i wrote few lines of code for it
if(array() == $myArray){
echo "Array";
}
or
if(array() === $myArray){
echo "Array";
}
I'm confused which one to use, as the second condition also checks type. But i think in the case of array we don't need to check their type.
Please anybody can suggest me which one to use.
you can check it by using empty() function like below
<?php
if(empty($myArray)) {
//condition
}
?>
if (! count($myArray)) {
// array is empty
}
Let php do its thing and check for booleans.
Use empty:
if (empty($myArray)) {
...
}
Try this :
<?php
$array = array();
if(empty($array))
{
echo "empty";
} else
{
echo "some thing!";
}
?>
It's always better to check first whether it is array or not and then it is empty or not. I always use like this because whenever I check only empty condition somewhere I don't get the expected result
if( is_array($myArray) and !empty($myArray) ){
.....
.....
}
<?php
if(empty($yourarry)){
}
OR
if(isset($yourarry)){
}
OR
if(count($yourarry)==0){
}
It depends:
Use count==0 if your array could also be an object implementing Countable
Use empty otherwise
array() == $myArray is unreadable, you should avoid it. You can see the difference between count and empty here.
This is one is confusing me.
I am trying to check if 2 vars are not in an array with an OR, but it returns the opposite results than the expected.
Does 2 !in_array, in conjunction with an OR, creates 2 negatives = positive?
The case:
$user->groups = array(2,13,15);
if ( !in_array(2, $user->groups) || !in_array(0, $user->groups) ) {
echo "Not in Array";
} else {
echo "In Array";
}
Since 2 is in the array, I expect the script to echo "In Array", but it echoes "Not in Array". If I remove the second !in_array after the OR, it echoes "In Array". If I change the OR with an AND, it echoes "In Array".
It doesn't make much sense, or I am just that confused at the moment. Can someone give some input?
The problem is you are using || instead of &&. What the logical OR (||) does is that it checks the first condition and if it is true then it does not test the other conditions in the if statement. Here is the revised code:
$user->groups = array(2,13,15);
if ( !in_array(2, $user->groups) && !in_array(0, $user->groups) ) {
echo "Not in Array";
} else {
echo "In Array";
}
Hope this helps!
Try this:
if ( !in_array(2, $user->groups) && !in_array(0, $user->groups) ) {
echo "Not in Array";
} else {
echo "In Array";
}
This will ensure that when both (&&) 0 and 2 are not in the array, it prints "Not in array"
As stated in my comment, you should be checking that the first value and the second value are not in the array: !in_array(2, $user->groups) && !in_array(0, $user->groups).
For two conditions, I would consider the following suggestion overkill but you may find it useful if you want to search for a larger number of values:
$arr = array(1,2,3);
$search = array(1,2);
$all_in = function($prev, $curr) use ($arr) {
return $prev && in_array($curr, $arr);
};
if (array_reduce($search, $all_in, true)) {
echo 'all values in $search are in $arr';
}
else {
echo 'some of the values in $search are not in $arr';
}
array_reduce applies the callback function $all_in to each of the values of the $search array and keeps track of a boolean value (initialised to true) that remains true as long as all the values are in the array $arr.
As I said, this approach isn't particularly useful if you're only looking for two values but one benefit is that you can easily add values to the $search array without changing any of the other code.
I want to go through every property my object has and check whether it is contained in a given string. The problem is, I now have 10 properties and wrote 10 if/else-cases. I think I can compromise it by writing a foreach loop
Currently it's like this
if (strpos($localWrapper->siteContents, $project->company_name) !== false)
echo "<br>true<br>";
else
echo 'false<br>';
if (strpos($localWrapper->siteContents, $project->company_street) !== false)
echo 'true<br>';
else
echo 'false<br>';
and so on.
There must be a way that I can go through every property of the project object and check whether it is contained in the siteContents-string and then print out a true or false depended on the result.
How could I achieve this?
You can loop through it:
foreach($project as $key=>$value){
echo $key.": (".$value.") ".strpos($localWrapper->siteContents, $value) !== false ? 'true' : 'false';
echo '<br />';
}
This is really basic though, if you've read the documentation on foreach, you could figure this out yourself :)
a simple google php loop through object gives A LOT of results, all doing the same :)
If your array has arrays as values, you need to go recursive. This functions checks if the value is a string. if so test it to your searchString. If it is an array, do the same for the new array
function SeeIfMyValuesMatch($searchString, $array){
foreach($array as $key=>$value){
echo $key.' ';
// Check if the value is an array, if so, go 1 deeper
if( is_array($value){
SeeIfMyValuesMatch($searchString, $value); // on deeper
}
else{
echo strpos($searchString, $value) ? 'true' : 'false'; // or echo
}
echo '<hr />'; // This is just for looks
}
}
SeeIfMyValuesMatch($project); // And start
Small sidenote: This may result in a weird looking text, I didnt make it pretty, just to show functionallity
I'm trying to teach myself PHP. My current exercise combines a form (not included in the code, but it works) that requires the user to enter the name of a city. The loop and the if statement compare the entry with an array of state capitals to return an answer that states whether that city is a state capital or not.
If I leave out the elseif part, the code runs ok, but I have no alternative when the user has entered a city that is not in the array. But with the elseif, the first part of the loop doesn't execute. For example, if I enter "Albany" without the elseif, I get "Albany is the capital of New York." But if I enter it with the elseif statement, it runs the loop until it finds "New York" and it prints "Albany is the capital of New York."
I've googled this, and I've read the books on PHP that I have. And I also know that I'm making a very basic mistake. Any guidance would be greatly appreciated.
for ($i = 0 ; $i < count($stateCapitalNames); $i++)
if ($enteredCity == $stateCapitalNames[$i]) {
print "<p>$enteredCity is the capital of <b>$stateNames[$i]</b>. </p>";
} elseif ($enteredCity != $stateCapitalNames[$i]){
print "<p>$enteredCity is not the capital of a state.</p>";
}
?>
You can use break to leave the for loop.
You should look at array_search to find the index you are looking for. array_search returns false if the capital does not exist.
For instance
$i = array_search($enteredCity, $stateCapitalNames);
if($i !== false)
{
echo "<p>$enteredCity is the capital of <b>",$stateNames[$i],"</b>. </p>";
}
You are missing your brackets in your for loop. I'm surprised the elseif is the culprit and that the code doesn't fail anyways. But here is what I would do, errors aside:
$correct = false;
for ($i = 0 ; $i < count($stateCapitalNames); $i++){
if ($enteredCity == $stateCapitalNames[$i]) {
$correct = true;
$stateNames = $stateNames[$i]; // Updated $stateNames variable
break;
}
}
//You can check $correct here...
if($correct){
print "<p>$enteredCity is the capital of <b>$stateNames[$i]</b>. </p>"; /*Removed [$i] from $stateNames. For some reason, $stateNames[$i] wasn't updating outside the loop, but now it is.
}
This way, no matter what, until the code finds a correct answer, the user is wronge. Once it finds the right answer, it sets it as correct and exits the loop by setting $i to the length of the array.
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=123123&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();
}