php if time with random number - php

I'm trying to echo a random date in a PHP loop, the code works for "if the post is 3 months old", then I want to get today's date, and minus the "random" number, eg will echo a date based on this number.
Everything is working, but not the $number. Can someone please tell me where I'm going wrong?
<?php
$post_age = date('U') - get_the_time('U');
if($post_age > 7884000 ) {
?>
<?php $number = 'UniqueRandomNumbersWithinRange(0,25,5)'; ?>
<?php echo date('jS F', strtotime("now -'.$number.' days") ); ?>
<?php } else {?>
<?php } ?>
with function:
function UniqueRandomNumbersWithinRange($min, $max, $quantity) {
$numbers = range($min, $max);
shuffle($numbers);
return array_slice($numbers, 0, $quantity);
}
Thanks :)

Two issues that I see there which are likely causing the issue, there are two occasions where you are turning things into strings but don't want to:
for
this isn't running the function because it's between single quotes ' ' so you want to remove them
<?php $number = UniqueRandomNumbersWithinRange(0,25,5); ?>
and for
You are mixing different types of quotes and so $number isn't really being called. You likely want to adjust it to something like:
<?php echo date('jS F', strtotime("now -".$number." days") ); ?>

You are confusing strings and functions several times in your code, as James' answer says.
Also, your UniqueRandomNumbersWithinRange() function returns an array. This cannot be written to a string.
<?php
$post_age = date('U') - get_the_time('U');
if($post_age > 7884000) {
$number = fetchRandoms(0, 25, 5);
echo date('jS F', strtotime("now -" . $number . " days") );
} else {
// la dee da
}
function fetchRandoms($min, $max, $amt) {
$result = '';
for ($i = 0; $i < $amt; $i++) {
$result .= mt_rand($min, $max);
}
return $result;
}

Related

Put an Echo inside the For Loop

I have seen all similar answers and they all tell us the same thing. But You do need a loop inside echo like a date selector with time?
Is there a nice way with just 1 For Loop to do all date & time?
Edit:
I am so sorry, my code indeed is terrible and functions just didn't cross my mind. I'll keep that in mind, all perfect answers thankyou!
That's why functions have been created...
function displayOptions($start, $end)
{
// insert here some tests on start and end
for($x = $start ; $x <= $end ; $x++) {
echo "<option value=\"$x\">$x</option>";
}
}
Create function and then use it:
function options($start, $end, $name, $label = '') {
echo "{$label}<select name='$name'><option></option>";
for($x = $start; $x <= $end; $x++) { echo "<option value='$x'>$x</option>"; }
echo "</select>";
}
options(1, 31, 'day', 'Date:');
options(1, 12, 'month', '/');
options(2012, 2022, 'year', '/');
options(0, 23, 'hour', 'Time:');
options(0, 59, 'minute', ':');
Create a function:
// $min contain start value
// $max contain end value
function create_list($min, $max) {
echo "<select name=''><option></option>";
for($x=$min;$x<=$max;$x++) { echo "<option value='$x'>$x</option>"; }
echo '</select>';
}
// call function as many time as you want to generate selectbox
create_list(1,31);
create_list(1,12);
create_list(2012,2022);
create_list(1,24);
create_list(1,59);

How to convert month name to month number

i want to convert month name to month number. By using this code, it is only show a result for december, the other month didnt work. But it is work if i change the year. For example, i choose November and 2015, the result is December and 2015. and if i choose November and 2014, the result is December and 2014.
The value in the database is 2015-09-28. i think there is a mistake on how i convert month name to month number. Can someone help me to fix my code.
This is my code :
VIEW
<?php echo form_open("announcement/announcement_result");?>
<?php echo form_dropdown('m', $m, set_value('m'), 'id="m"'); ?>
<?php echo form_dropdown('q', $q, set_value('q'), 'id="q"'); ?>
<?php echo form_submit('search', 'SEARCH', 'class="button expand"'); ?>
<?php echo form_close(); ?>
CONTROLLER
function announcement_list()
{
$data['q'] = array(
'' => ' Select Year',);
for ($i = 0; $i < 10; $i++)
{
$date = date('Y') - $i;
$data['q'][$date] = $date;
}
$m = '';
$data['m'] = $m;
$data['m'] = array(
'' => 'Select Month',
);
for ($m = 1; $m <= 12; $m++) {
$month = date("F", mktime(0, 0, 0, $m));
$data['m'][$month] = $month;
}
if ($m='December')
{
$m='12';
}
else if($m='November')
{
$m='11';
}
else if ($m='October')
{
$m='10';
}
else if ($m='September')
{
$m='9';
}
else if ($m='August')
{
$m='8';
}
else if ($m='July')
{
$m='7';
}
else if ($m='June')
{
$m='6';
}
else if ($m='May')
{
$m='5';
}
else if ($m='April')
{
$m='4';
}
else if ($m='March')
{
$m='3';
}
else if ($m='February')
{
$m='2';
}
else if ($m='January')
{
$m='1';
}
$data['results'] = $this->news_model->get_announcement_list($config['per_page'], $page);
}
MODEL
function get_results($m, $q, $limit=6, $offset=0)
{
$sql = "SELECT *
FROM ArkibBerita
WHERE code='PENGUMUMAN' AND Enable = 'Y' AND Lang ='EN' AND YEAR(BeritaDate)='{$q}' AND MONTH(BeritaDate)='{$m}'
ORDER BY position ASC
OFFSET {$offset} ROWS
FETCH NEXT {$limit} ROWS ONlY";
$query = $this->db->query($sql);
return $query->result();
}
What about:
echo date('m', strtotime('january'));
Output:
01
If you don't want the leading zero use n or see the manual for other usages; http://php.net/manual/en/function.date.php.
In your code you aren't comparing the date, you are setting it.
if ($m='December')
Should be
if ($m=='December')
One equals sets. Two equals compares. Three equals compares and requires the same variable type. http://php.net/manual/en/language.operators.comparison.php
So on every iteration your $m is going to be 12 because the $m always sets to the string and that is the first condition it hits. If you inverted your order it would be set to 1.
You also should look into using prepared statements for your SQL queries. http://php.net/manual/en/security.database.sql-injection.php

How can I remove last digit from decimal number in PHP

I want to remove last digit from decimal number in PHP.
Lets say I have 14.153. I want it to be 14.15. I will do this step till my number is no longer decimal.
I think this should work:
<?php
$num = 14.153;
$strnum = (string)$num;
$parts = explode('.', $num);
// $parts[0] = 14;
// $parts[1] = 153;
$decimalPoints = strlen($parts[1]);
// $decimalPoints = 3
if($decimalPoints > 0)
{
for($i=0 ; $i<=$decimalPoints ; $i++)
{
// substring($strnum, 0, 0); causes an empty result so we want to avoid it
if($i > 0)
{
echo substr($strnum, 0, '-'.$i).'<br>';
}
else
{
echo $strnum.'<br>';
}
}
}
?>
echo round(14.153, 2); // 14.15
The round second parameter sets the number of digits.
You can try this.
Live DEMO
<?php
$number = 14.153;
echo number_format($number,2);

If value is greater/lesser than xyz

I have a value as a number. For instance, 502.
I want to write a php if statement that will display some text if the value is lesser or greater than certain numbers, or between a range.
E.g.
number is 502, text will say: "Between 500-600"
number is 56, text will say: "Between 0-60"
etc.
So far I have this:
<?php $count=0;?>
<?php $board = getUserBoard($userDetails['userId']);?>
<?php if(is_array($board)):?>
<?php $boardCount = count($board);?>
<?php foreach($board as $key=>$value):?>
<?php
$boardPin = getEachBoardPins($value->id);
$count = $count + count($boardPin);
?>
<?php endforeach?>
<?php endif?>
And that gives me a number:
<?php echo $count;?>
I have tried writing...
<?php if(($count)): => 500 ?>
Over 500
<?php endif ?>
But I keep running into errors.
I'd like to create a list if possible with elseif statements denoting various number ranges.
E.g.
0-50, 51-250, 251-500 etc.
Can anyone help me?
Thanks.
The sanest, neatest and most widely used syntax for if conditions in PHP is:
if($value >=500 && $value <=600 )
{
echo "value is between 500 and 600";
}
if ($count >= 0 && $count < 100) {
echo 'between 0 et 99';
} elseif ($count < 199) {
echo 'between 100 and 199';
} elseif { ...
}elseif ($count < 599) {
echo 'between 500 and 599';
} else {
echo 'greater or equal than 600';
}
I wrote something like this a few years back (might be a better way to do it):
function create_range($p_num, $p_group = 1000) {
$i = 0;
while($p_num >= $i) {
$i += $p_group;
}
$i -= $p_group;
return $i . '-' . ($i + $p_group - 1);
}
print 'The number is between ' . create_range(502, 100) . '.';
It'll say 500-599, but you can adjust it to your needs.
I'm not sure what you need, but here is what I understand you ask:
function getRange($n, $limit = array(50, 250, 500)) { // Will create the ranges 0-50, 51-250, 251-500 and 500-infinity
$previousLimit = 0;
foreach ($limits as $limit) {
if ($n < $limit) {
return 'Between ' . ($previousLimit + 1) . ' and ' . $limit; //Return whatever you need.
}
$previousLimit = $limit;
}
return 'Greater than ' . $previousLimit; // Return whatever you need.
}
echo getRange(56); // Prints "Between 51 and 250"
echo getRange(501); // Prints "Greater than 500"
echo getRange(12, array(5, 10, 15, 20)); // Prints "Between 11 and 15"
function getRange($number){
$length=strlen($number);
$length--;
$r1=round($number,-$length);
if ($r1>$number){
$r2=$r1-pow(10,$length);
return ''.$number.' value is between '.$r2.'-'.$r1;
}
else {
$r2=$r1+pow(10,$length);
return ''.$number.' value is between '.$r1.'-'.$r2;
}
}
Try this.

Wordpress php, get_the_title() coming out empty when run through substr & strrchr

I'm currently working on a Wordpress site. And what the client wants is to be able to create a schedule for a convention. What he is asking for is the option of clicking a button in each post which would add a 15 minute Q&A slot.
The way I went about the time was to use the title of a post which would be written as 11:20 AM - 11:40 AM
the problem I'm having is that the get_the_title() function comes out empty when used in a substr & strrchr. The interesting thing is when I put it as "11:20 AM - 11:40 AM" instead of get_the_title() it comes up fine.
By the way I'm still pretty new with php so Im probably not going about it the right way.
my code
echo qatime(get_the_title(), "AM");
and the code in the functions.php file is
function qatime($string, $cat){
$newCat = $cat;
$stringsplit = substr(strrchr($string, "-"), 1);
$pieces = explode(":", $stringsplit);
$firstnum = preg_replace("/[^0-9]/", '', $pieces[0]);
$lastnum = preg_replace("/[^0-9]/", '', $pieces[1]);
$qaTime = 15;
$minute = $lastnum + $qaTime;
if($minute < 60){
} else {
$firstnum += 1;
$minute -= 60;
}
if($firstnum >= 12){
$firstnum -= 12;
if($firstnum == 0){
$firstnum = 12;
}
$newCat = 'PM';
}
if($pieces[0] == 12){
$cat = 'PM';
}
$minutes = str_pad($minute, 2, "0", STR_PAD_LEFT);
return $stringsplit." ".$cat." - ".$firstnum.":".$minutes." ".$newCat;
}
Solved
Thanks for the quick responses.
I found that instead of using get_the_title(), $post->post-title made it work.
$string = $post->post_title;
echo qatime($string,'AM');

Categories