PHP: pass internal date() function as function parameter? - php

I wonder if this is possible somehow …
function get_event_list( $year = date('Y') ) {
}
So I could call this function like get_event_list(2012), but when not adding a para it always retrieves all events from the current year (2014);
Kind Regards,
Matt

The best way to achieve it is to do:
function get_event_list( $year = null ) {
if ( is_null($year) ) {
$year = date('Y');
}
}

You can't use a built-in function as the default argument.
From the PHP manual:
The default value must be a constant expression, not (for example) a variable, a class member or a function call.
What you need can be achieved as follows:
function get_event_list($year = null) {
if(!isset($year)) {
$year = date('Y');
}
}

You could make the parameter nullable like so:
function get_event_list( $year = NULL ){
$year = is_null( $year) ? date('Y') : $year;
//Code here
}
A way to call this function would be get_event_list(2012) or get_event_list()

You can do it like this
function get_even_list($year = ""){
if(empty($year)){
$year = date('Y');
}
// Whatever you wann do here
}
Steve

Related

Date Validation Codeigniter

I'm creating a validation for the post in my Controller.
I have a problem about the date.
I have created in applications/libraries a MY_Form_validation.php page in which I wrote this:
public function valid_date($date, $format = 'Y-m-d') {
$d = DateTime::createFromFormat($date, $format);
return $d && $d->format($format) === $date;
}
Then I have created the form_validation_lang.php with
<?php
$lang['form_validation_valid_date'] = 'The field {field} is not a valid date';
While in my controller I have:
//load the libraries
$this->form_validation->set_rules('birthdate', 'birthdate', 'trim|required|valid_date');
if($this->form_validation->run() == FALSE){
$errors = $this->form_validation->error_array();
var_dump($errors);
$this->response($errors, 500);
return;
}
$person = array(
//..
'birthdate' => $this->post('birthdate'),
//...
);
It prints me that:
'birthdate' => 'string'
About my DB at the beginning my field was Data, and i received this error. Than I have changed to Datetime but the error is the same.
Now it's:
birthdate date NOT NULL,
Now for example I'm trying to post a date like '1960-04-20' and I receive back the error:
"birthdate": "The field birthdate is not a valid date"
I want to write in the db only the date and not the time, could be this the problem??
How can I do to validate date?
Thank you
Replace your function with next:
public function valid_date($date, $format = 'Y-m-d') {
$d = new DateTime($date);
return $d && $d->format($format) === $date;
}
Demo
Or with next one:
public function valid_date($date, $format = 'Y-m-d') {
$d = DateTime::createFromFormat($format,$date); // <-- replace arguments
return $d && $d->format($format) === $date;
}
Demo
DateTime::createFromFormat() documentation
You need to cast this string, after success validation, into DATE datatype and only then send it into DB. Or you can write "to_date($stringvar,$format)" in your SQL query.
Seems like CodeIgniter doesn't likes default variables in validation options. I mean, you can't declare $format = 'Y-m-d' as an argument. So, it would work if you won't use it:
public function valid_date_dmY($str)
{
$d = DateTime::createFromFormat('d.m.Y',$str);
return $d && $d->format('d.m.Y') === $str;
}

How Can we pass function parameter as another function which itself has different parameters?

I have function below :
function cache_activity_data($cid,$somefunction) {
$cache_time = '+15 minutes';
$cache_id = $cid;
$expire = strtotime($cache_time);
$cache = cache_get($cache_id);
if (!empty($cache->data)) {
if (time() > $cache->expire) {
cache_clear_all($cache_id, 'cache_custom_activity_dashboard');
$report = $somefunction; // will get from function
cache_set($cache_id, $report, 'cache_custom_activity_dashboard', $expire);
}
else {
$report = $cache->data;
}
}
else {
$report = $somefunction; // will get from function
cache_set($cache_id, $report, 'cache_custom_activity_dashboard', $expire);
}
return $report;
}
Now $somefunction can be like below examples :
total_comments_per_user($user->uid);
total_comments_per_user_time_limit($user->uid, $user_year_start);
total_revisions_time_limit($month_ago);
total_revisions_time_limit($year_start);
every time I need to pass like 20 different functions. Is that possible I am getting error as at place of varibales I am passing function But I am not able to figure is that possible.
How I want to use :
//want to write this as function
$cache_revisions_total = cache_get("total_revisions", "cache_custom_activity_dashboard");
if (!empty($cache_revisions_total->data)) {
if (time() > $cache_revisions_total->expire) {
cache_clear_all("total_revisions", 'cache_custom_activity_dashboard');
$t_revisions = total_revisions();
cache_set("total_revisions", $t_revisions, 'cache_custom_activity_dashboard', $expire);
}
else {
$t_revisions = $cache_revisions_total->data;
}
}
else {
$t_revisions = total_revisions();
cache_set("total_revisions", $t_revisions, 'cache_custom_activity_dashboard', $expire);
}
// want to write this as function end here
$vars['total_bubbla_rev'] = number_format(($t_revisions / $days_from_rev_start), 2, '.', '');
// here i want to do same so i need to write function or should i repeat code
$y_revisions = total_revisions_time_limit($year_start);
$vars['yearly_bubbla_rev'] = number_format(($y_revisions / $year_days), 2, '.', '');
// here i want to do same so i need to write function or should i repeat code
$m_revisions = total_revisions_time_limit($month_ago);
$vars['monthly_bubbla_rev'] = number_format(($m_revisions / 30), 2, '.', '');
Please suggest, Thanks!
I see two possible options.
Option 1
You could use Anonymous functions. I simplified your function but you'll get the idea:
function cache_activity_data($cid, $somefunction) {
$report = $somefunction();
}
Define your functions as anonymous functions:
$parm1 = "banana";
$parm2 = "fruit";
$your_function1 = function() use ($parm1, $parm2) {
echo "$parm1 is a $parm2";
};
$your_function2 = function() use ($parm1) {
echo $parm1;
};
Usage:
cache_activity_data($cid, $your_function1); // shows "banana is a fruit"
cache_activity_data($cid, $your_function2); // shows "banana"
Read carefully through the documentation. Especially the part about variable scopes.
Option 2
Another possibility is call_user_func_array() but this requires you to make a little adjustment to cache_activity_data(). You need to add a third parameter which holds an array:
function cache_activity_data($cid, $somefunction, $somefunction_parms) {
$report = call_user_func_array($somefunction, $somefunction_parms);
}
Define your functions as usual:
function your_function1($parm1, $parm2) {
echo "$parm1 is a $parm2";
}
function your_function2($parm) {
echo $parm;
}
Usage
cache_activity_data($cid, "your_function1", array("banana", "fruit")); // shows "banana is a fruit"
cache_activity_data($cid, "your_function2", array("banana")); // shows "banana"
First, you cannot pass functions as parameters, however you can use callbacks as explained here:
http://php.net/manual/en/language.types.callable.php
But in your case, this seems irrelevant as you are not determining the function or changing its value in cache_activity_data().
Therefore, you might want to do like this:
$reportDefault = total_comments_per_user($user->uid);
// Or ... $reportDefault = total_revisions_time_limit, total_comments_per_user_time_limit, etc..
$report = cache_activity_data($cid, $reportDefault);
You do not need to add pass $report or any function as parameter.

Storing time in array

I have some code that stores values in an array. It all seems to work but I also want to store the time that each value is added to the array (as part of the array) The code stores only unique values to a maximum of four.
function getBand() {
$band_name=$_GET['band_name'];
return $band_name;
}
$pages=$_SESSION['pages'];
if(in_array($_GET['band_name'], $pages)) {
echo"Already in Array";
} else {
if (empty($_SESSION['pages']))
$_SESSION['pages'] = array();
$_SESSION['pages'][] = getBand();
$_SESSION['pages'] = array_slice($_SESSION['pages'], -4);
}
Use time () to get the time.
And store that in the desired array.
array_push ($array, time ());
Since you're talking about "the time they are added to the array" it could be that you mean microseconds which in that case use microtime ()
Note that both functions don't return a formatted timestamp, instead they return an integer.
More on time () here
More on microtime () here
Maybe something like this could do the work:
$test = "Metallica";
$test2 = "The Black Keys";
$arr['pages'][$test] = $test;
$arr['pages'][$test] = date("D M d, Y G:i");
$arr['pages'][$test2] = $test;
$arr['pages'][$test2] = date("D M d, Y G:i");
echo '<pre>'.print_r($arr, true).'</pre>';
For date format you can see - http://php.net/manual/bg/function.date.php
Cheers
class SessionManager
{
protected static $pages = null;
protected static $maxPages = 4;
public function __construct($session) {
self::$pages = $session['pages'];
}
public static function addPage($pageName) {
self::$pages[$pageName] = array(
'name' => $pageName,
'created' => date('Y-m-d h:i:s')
);
self::$pages = array_slice(self::$pages, -1 * $maxPages);
}
public static function writeSession(&$session) {
$session['pages'] = self::$pages;
}
public static function getPages() {
return self::$pages;
}
}
session_start();
$session = new SessionManager($_SESSION);
$session->addPage($_GET['band_name']);
$session->writeSession($_SESSION);
print_pre($session->getPages());

PHP Optional Function Arguments

I'm a little stuck trying to create a function that takes a single, optional argument. Instead of this being a string I'd like it to be the result of a function (or even better, a DateTime object). Essentially - I want the user to either pass in a DateTime object, or for the function to resort to todays date if no arguments are supplied. Is this possible with PHP? By trying to create the new object in the function header as such
function myDateFunction($date = new DateTime()){
//My function goes here.
}
causes PHP to fall over.
Many thanks.
Yes. It is possible if you move $date instantiation to function body:
<?php
header('Content-Type: text/plain');
function myDateFunction(DateTime $date = null){
if($date === null){
$date = new DateTime();
}
return $date->format('d.m.Y H:i:s');
}
echo
myDateFunction(),
PHP_EOL,
myDateFunction(DateTime::createFromFormat('d.m.Y', '11.11.2011'));
?>
Result:
15.09.2013 17:25:02
11.11.2011 17:25:02
From php.net:
Type hinting allowing NULL value
The default value must be a constant expression, not (for example) a variable, a class member or a function call.
http://php.net/manual/en/functions.arguments.php#example-154
You can do it this way:
function myDateFunction($date = null){
if(is_null($date) || !($date instanceof DateTime)) {
$date = new DateTime();
}
return $date;
}
var_dump(myDateFunction());
You can use other option:
function myDateFunction($date = null){
if(is_null($date)) $date = new DateTime();
}
function myDateFunc($date = null){
if(!isset($date) || $date !instanceof DateTime){
$date = new DateTime()
}
/* YOur code here*/
}
for optional argument in your function, you can write code like
function myDateFunction($date = ''){
//My function goes here.
if($date==''){ $date = new DateTime()}
}
hope it helps

Function to check if a string is a date

I am trying to write a function to determine if a string is a date/time using PHP. Basically a valid date/time would look like:
2012-06-14 01:46:28
Obviously though its completely dynamic any of the values can change, but it should always be in form of XXXX-XX-XX XX:XX:XX, how can I write a regular expression to check for this pattern and return true if matched.
If that's your whole string, then just try parsing it:
if (DateTime::createFromFormat('Y-m-d H:i:s', $myString) !== false) {
// it's a date
}
Easiest way to check if a string is a date:
if(strtotime($date_string)){
// it's in date format
}
Here's a different approach without using a regex:
function check_your_datetime($x) {
return (date('Y-m-d H:i:s', strtotime($x)) == $x);
}
In case you don't know the date format:
/**
* Check if the value is a valid date
*
* #param mixed $value
*
* #return boolean
*/
function isDate($value)
{
if (!$value) {
return false;
}
try {
new \DateTime($value);
return true;
} catch (\Exception $e) {
return false;
}
}
var_dump(isDate('2017-01-06')); // true
var_dump(isDate('2017-13-06')); // false
var_dump(isDate('2017-02-06T04:20:33')); // true
var_dump(isDate('2017/02/06')); // true
var_dump(isDate('3.6. 2017')); // true
var_dump(isDate(null)); // false
var_dump(isDate(true)); // false
var_dump(isDate(false)); // false
var_dump(isDate('')); // false
var_dump(isDate(45)); // false
In my project this seems to work:
function isDate($value) {
if (!$value) {
return false;
} else {
$date = date_parse($value);
if($date['error_count'] == 0 && $date['warning_count'] == 0){
return checkdate($date['month'], $date['day'], $date['year']);
} else {
return false;
}
}
}
I use this function as a parameter to the PHP filter_var function.
It checks for dates in yyyy-mm-dd hh:mm:ss format
It rejects dates that match the pattern but still invalid (e.g. Apr 31)
function filter_mydate($s) {
if (preg_match('#^(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)$#', $s, $m) == false) {
return false;
}
if (checkdate($m[2], $m[3], $m[1]) == false || $m[4] >= 24 || $m[5] >= 60 || $m[6] >= 60) {
return false;
}
return $s;
}
Although this has an accepted answer, it is not going to effectively work in all cases. For example, I test date validation on a form field I have using the date "10/38/2013", and I got a valid DateObject returned, but the date was what PHP call "overflowed", so that "10/38/2013" becomes "11/07/2013". Makes sense, but should we just accept the reformed date, or force users to input the correct date? For those of us who are form validation nazis, We can use this dirty fix: https://stackoverflow.com/a/10120725/486863 and just return false when the object throws this warning.
The other workaround would be to match the string date to the formatted one, and compare the two for equal value. This seems just as messy. Oh well. Such is the nature of PHP dev.
A simple solution is:
echo is_numeric( strtotime( $string ) ) ? 'Yes' : 'No';
if (strtotime($date) > strtotime(0)) {
echo 'it is a date'
}
I found my answer here https://stackoverflow.com/a/19271434/1363220, bassically
$d = DateTime::createFromFormat($format, $date);
// The Y ( 4 digits year ) returns TRUE for any integer with any number of digits so changing the comparison from == to === fixes the issue.
if($d && $d->format($format) === $date) {
//it's a proper date!
}
else {
//it's not a proper date
}
I wouldn't use a Regex for this, but rather just split the string and check that the date is valid:
list($year, $month, $day, $hour, $minute, $second) = preg_split('%( |-|:)%', $mydatestring);
if(!checkdate($month, $day, $year)) {
/* print error */
}
/* check $hour, $minute and $second etc */
If your heart is set on using regEx then txt2re.com is always a good resource:
<?php
$txt='2012-06-14 01:46:28';
$re1='((?:2|1)\\d{3}(?:-|\\/)(?:(?:0[1-9])|(?:1[0-2]))(?:-|\\/)(?:(?:0[1-9])|(?:[1-2][0-9])|(?:3[0-1]))(?:T|\\s)(?:(?:[0-1][0-9])|(?:2[0-3])):(?:[0-5][0-9]):(?:[0-5][0-9]))'; # Time Stamp 1
if ($c=preg_match_all ("/".$re1."/is", $txt, $matches))
{
$timestamp1=$matches[1][0];
print "($timestamp1) \n";
}
?>
If you have PHP 5.2 Joey's answer won't work. You need to extend PHP's DateTime class:
class ExDateTime extends DateTime{
public static function createFromFormat($frmt,$time,$timezone=null){
$v = explode('.', phpversion());
if(!$timezone) $timezone = new DateTimeZone(date_default_timezone_get());
if(((int)$v[0]>=5&&(int)$v[1]>=2&&(int)$v[2]>17)){
return parent::createFromFormat($frmt,$time,$timezone);
}
return new DateTime(date($frmt, strtotime($time)), $timezone);
}
}
and than you can use this class without problems:
ExDateTime::createFromFormat('d.m.Y G:i',$timevar);
function validateDate($date, $format = 'Y-m-d H:i:s')
{
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) == $date;
}
function was copied from this answer or php.net
This solves for me, but also presents various other problems I think.
function validateTimeString($datetime, $format = "Y-m-d H:i:s"){
return ($datetime == date($format, strtotime($datetime)));
}
When I work with unconventional APIs, I sometimes get a bit of a messy return instead of a well defined date format. So I use a rather inelegant class and I readily admit that it is brutal and unconventional in principle but it does me good sometimes ^^.
class DateHelper
{
private const DATE_FORMATS = [
DATE_ATOM,
DATE_COOKIE,
DATE_RFC822,
DATE_RFC850,
DATE_RSS,
DATE_W3C,
"Y-m-d\TH:i:s.u",
'Y-m-d\TH:i:s',
"Y-m-d'T'H:i:s.SSS'Z'",
"Y-m-d\TH:i:s.uP",
"Y-m-d\TH:i:sP",
"d/m/Y H:i:s",
];
/**
* #param string $inputStringDate
* #return DateTime|null
*/
public static function createDateFromUnknownFormat(string $inputStringDate): ?DateTime
{
$inputStringDate = str_replace('/', '-', $inputStringDate);
preg_match('/^(\d{4})\-(\d{2})-(\d{2})$/', $inputStringDate, $result);
if (!empty($result)) {
return DateTime::createFromFormat('Y-m-d', $inputStringDate);
}
preg_match('/^(\d{2})\-(\d{2})-(\d{4})$/', $inputStringDate, $result);
if (!empty($result)) {
return DateTime::createFromFormat('d-m-Y', $inputStringDate);
}
foreach (self::DATE_FORMATS as $dateFormat) {
if ($dateObject = DateTime::createFromFormat($dateFormat, $inputStringDate)) {
return $dateObject;
}
}
return null;
}
}
strtotime? Lists? Regular expressions?
What's wrong with PHP's native DateTime object?
http://www.php.net/manual/en/datetime.construct.php

Categories