I'm trying to find the best way to compare dates outside a while statement. I wrote a function and set the while loop inside. Taking in account that I need to compare every single date from the loop with $this_new_date, how can I achieve this?
function getDates(){
$returnDates = array();
while($result = mysqli_fetch_array($allDatesQuery)){
$returnDates[] = date("Y-n-j",strtotime($result['date']));
}}
if($returnDates===$this_new_date){
//do something here
}
Please note that if you are going to use the MySQLi extension (http://php.net/manual/en/book.mysqli.php) you will need to use a while loop to store your data unless you are running PHP >= 5.3 in which case you can use mysqli_fetch_all (http://php.net/mysqli_fetch_all).
Option 1
Perform the date comparison inside the query. This is going to be your absolute best/fastest option. That way PHP does not even need to do anything.
Example:
SELECT * FROM table WHERE date = ?;
Then use a prepared statement to pass your date value to the query: http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
Option 2
Assuming you need to perform this date comparison in PHP the while loop is still going to be the fastest because unless the date you're looking for is the very last record you can likely get away without having to read the entire query result.
function is_date_in_query($this_new_date, $allDatesQuery) {
while($result = mysqli_fetch_array($allDatesQuery)) {
if (strtotime($this_new_date) == strtotime($result['date'])) {
return TRUE;
}
}
return FALSE;
}
if (is_date_in_query($this_new_date, $allDatesQuery)) {
// yes the date is inside - do something
}
else {
// no the date is not inside - do something else
}
But you say you cannot use a while loop so let's look at another option.
Option 3
Use a combination of mysqli_fetch_all, in_array and array_column. This prevents any while loops but requires you to load the entire query result.
Example:
// Put ALL rows into an array
$result_array = mysqli_fetch_all($allDatesQuery, MYSQLI_ASSOC);
// Check if the date is anywhere in the result array
if (in_array(date('Y-m-d', strtotime($this_new_date)), array_column($result_array, 'date'))) {
// yes the date is inside - do something
}
else {
// no the date is not inside - do something else
}
Here is a working example (updated): https://eval.in/868105
you could do something like this:
...
$matchedDates = array_filter($returnDates, function($value) use($this_new_date){
return $value == $this_new_date;
});
var_dump($matchedDates);
Related
I need a program in PHP, when I search a number in a given series like 1,3,7,15,31... and if it is present in the series then give output as the index on which it is present in series?
LIKE I HAVE DONE SOMETHING TO DO THIS BUT FAILED.
<?php
function test1($n) {
for($i=1;$i<=$n;$i=$c) {
$c =1 + (2 * $i);
}
}
function test2($p) {
global $c,$n;
$input=array(1);
$in=array_push($input,$c);
$k=array_search($p,$input);
$flipped = array_flip($k);
var_dump($flipped);
}
test1(1000000);
test2(45);
Like in this program I had made two functions and in FUNCTION test1 I made a formula to make the series 1,3,7,15,31,63,127.... and in FUNCTION test2 I insert a number in form of parameter and want to SEARCH that number in the series that I form above and the I want OUTPUT as the index of that number searched.
Also if the number is not present in the series then I want the output as the nearest number of the number I search.
HELP.!!!
Thank You
You've got a few problems with this code.
function test1($n) {
for($i=1;$i<=$n;$i=$c) {
$c =1 + (2 * $i);
}
}
The first problem here is that you don't do anything with $c each time you increment it. You should probably be pushing it into an array of series integers.
Secondly you don't return a result, so you can't actually use the series you would've created.
You could use something like this instead:
function test1($limit) {
$series = [];
for ($i = 1; $i <= $limit; $i = $i * 2 + 1) {
$series[] = $i;
}
return $series;
}
Next, your test2 function:
function test2($p) {
global $c,$n;
$input=array(1);
$in=array_push($input,$c);
$k=array_search($p,$input);
$flipped = array_flip($k);
var_dump($flipped);
}
Ok, first don't use global variables. Pass the ones you need in as arguments and again, return the result. To be perfectly honest, I'm not entirely sure what this function is supposed to do. All you need is the array_search call which "searches the array for a given value and returns the first corresponding key if successful".
For example:
function test2($series, $number) {
return array_search($number, $series);
}
Using these, you can do something like this:
$series = test1(1000000);
var_dump(test2($series, 45)); // bool(false)
var_dump(test2($series, 31)); // int(4)
Also if the number is not present in the series then I want the output as the nearest number of the number I search.
Ok, you'll need to write some custom logic for this. I suggest you run your array_search check, then if it returns false you loop through your series and check the following criteria:
The previous series entry is lower than your number
The next series entry is higher than your number
Then return whichever of those two has a smaller absolute difference when you subtract the series entry from your number.
I'm not going to write an example for this because it smells a bit like a school assignment, which I'm sure you're capable of doing =) good luck.
I have some fairly complex MySQL queries that return about 30 fields.
I am doing some conditional formatting for a report and need to determine if any of those fields are empty across all of the results.
I know how to check on a per row basis, but I need to determine if an entire "column" is empty after returning the results.
I'm using PHP 5.2 and simple HTML to generate the reports.
Something like this?
$results = mysql_fetch_array($resource);
$columnEmpty = checkEmptyColumn($results, "column_name"); // returns true if empty
function checkEmptyColumn($array, $columnName){
foreach ($array as $arr){
if(!empty($arr[$columnName])) return false;
}
return true;
}
I will be reusing a Drupal db_query result set unpacking function many, many times in my code for a variety of different queries - I am using O-O and as such I want to reuse it and be as 'DRY' as possible.
Therefore I have tried to strip it down to the most generic functions so that as long as the $columns supplied match the columns used in the query and similarly in the $resultset, I can loop and assign values to keys, as is shown, and return a $rows[].
I've not yet come across the issue of trying to use a variable's value as a variable name (the $key), if it's just something I should avoid entirely, please say.
foreach($this->resultSet as $aRecord) {
$c = 0;
while (isset($this->columns[$c])) {
$value = $this->columns[$c];
$rows[$i] = array(
$key[$this->columns[$c]] => $aRecord->$value,
);
$c++;
}
$i++;
}
I've read through the following and am beginning to think this is just knowledge I'm missing in my PHP experience so far.
Can I use a generated variable name in PHP?
PHP use function return value as array
https://wiki.php.net/rfc/functionarraydereferencing
It felt wrong, and someone once told me that if you have to start writing complex functions in PHP you've probably missed an available function PHP already offers.. so true... thanks to (at the time of writing...) 'MrCode' for this suggestion.
$this->sql = "SELECT foo, bar FROM foobar";
$this->result = db_query($this->sql);
if ($this->result->rowCount() > 0) {
while ($row = $this->result->fetchAssoc()) {
$this->resultArray[] = $row;
}
}
Learning PHP and I have a question.
How does one obtain an element from an array and determine if it is equal to a static value? I have a return set from a query statement (confirmed the array has all values).
I tried:
<? if($row["rowValue"] == 1) {
}
?>
I was expecting the value to be 1, but it's returning null (as if I'm doing it wrong).
You're pretty much there; something like this should confirm it for you:
echo "<p>Q: Does ".$row["rowValue"]." = 1?</p>";
if($row["rowValue"] == 1) {
echo "<p>A: Yes ".$row["rowValue"]." does equal 1</p>";
} else {
echo "<p>A: No, '".$row["rowValue"]."' does not equal 1</p>";
}
If that's still returning 'No' you could try viewing the whole of the $row array by doing a var dump of the array like so:
var_dump($row);
This will give you detailed output of how the array is built and you should be able to see if you are calling the correct element within the array.
What is returning null?
Try this:
if($row["rowValue"] === 1) { ... }
Make sure there is an element in $row called rowValue.
maybe try:
<? if($row[0]["theNameOfAColumn"] == 1) {
}
?>
Usually databases return rows like row[0], row[1], row[2], etc.
I am not sure what exactly you are doing, but try using array_filp() which will Exchanges all keys with their associated values
than you can do like
if($row["rowValue"] == 1) {
http://in1.php.net/manual/en/function.array-flip.php
If you're pulling it from mysqli_fetch_row then it wants a number, not a column name. If it's being pulled from mysqli_fetch_array then it will accept a column name.
http://php.net/manual/en/mysqli-result.fetch-row.php
http://php.net/manual/en/mysqli-result.fetch-array.php
I am trying to get multiple value from user input from text field and want to explode or keep adding into if condition statement
Here is my code
foreach ($list['post'] as $item) {
if( ($item['single']['catid'] != 8) AND ($item['single']['catid'] != 4) ){
$this->list_post($item);
}
}
Now what exactly I am looking for is in if( ($item['single']['catid'] != 8) AND ($item['single']['catid'] != 4) ) I want allow user to add multiple category ID and each ID will add AND and further id code AND ($item['single']['catid'] != 4)
I never done this before and don't know either this is proper way to do or any other possible better way.
Thanks a lot
You should have some kind of an array of the category IDs you want to check for, for example:
$categories = array(8, 4);
Then you could use something like the in_array(needle, haystack) built-in function of PHP.
Your if condition would become like that one: if (!in_array($item['single']['catid'], $categories)) {.
You should be using the above, but I am going to give you an idea of how it works, so you can understand the principle for more complex issues:
function exists($target, $array) {
foreach ($array as $element) { // Go through each element in the array
if ($element == $target) { // Check to see if any element there is what you are searching for
return true; // Return true, that it does exist, and stop there.
} else {
// Just ignore it...
}
}
return false; // If you get here, it means nothing returned true, so it does not exist...
}
To be used as if (exists($item['single']['catid'], $categories)) {.
It wouldn't work if it was "inside" the if statement because you have to do some processing before evaluating if it exists or not. So you either could have done that before the if statement, and store the result in a variable, or use a function (which PHP provides).
Hopefully the concept will help you fir more complex problems...
Note: this assumes your input is in the form of an array, which you can build via various ways, if not provided as is directly.
Update:
The input you get via the input field is sent through form, to which you specify either POST or GET as a method. Assuming it is POST that you are using, this is how you'd get the input as a string as it was entered in the text field:
$categories_string = $_POST['the_name_field_in_the_input_tag'];
After that you have to understand it as a list of items, let's say separated by commas: 1,3,5,8. Then this is simply separating by commas. You can use explode($delimiter, $string). Like that:
$categories_array = explode(',', $_POST['categories']);
But you cannot trust the input, so you could get something like 1, 2, 3,5,6. The spaces will mess it up, because you will have spaces all around. To remove them you can use trim for example.
$categories = array(); // Create the array in which the processed input will go
foreach ($categories_array as $c) { // Go through the unprocessed one
$categories[] = trim($c) * 1; // Process it, and fill the result. The times one is just so that you get numbers in the end and not strings...
}
Then you can use it as shown earlier, but keep in mind that this is just an example, and you might not even need all these steps, and there are much more efficient ways to process this input (regular expressions for example). But the concern here is not sanitizing input, but keep in mind you will need to do that eventually.
Hope it's clear enough :)
You might be better off with in_array() for checking a value against a variable number of possibilities.
I'm not sure I understand your problem. You want user to be able to input different values, e.g.:
$string = "5, 6, 7, 8, 10";
Afterwards, you want to check if 'catid' is not in that array and if it isn't you want to run $this->list_post($item);
If so, then you should use something like this:
$values = explode(", ", $string); //make array from values
foreach ($list['post'] as $item) {
if (!in_array($item['single']['catid'], $values)) { //check whether catid is in array
$this->list_post($item); // execute whatever you want
}
}
Hope it helps.