PHP – Round a value up to the nearest multiple value

php-banner

round(), ceil() and the like to a good job of most things in PHP.

But what if you need to round the number up to the nearest 10 or nearest 15 etc.  This little function makes this easy:

function roundToNearestMultiple($value, $roundTo)
{
    $mod = $value%$roundTo;
    return $value+($mod<($roundTo/2)?-$mod:$roundTo-$mod);
}

Usage:

$number= roundToNearestMultiple($input, 10);

/* 
    Outputs:
      $input= 7 -> $number= 10
      $input= 85 -> $number= 90
*/

$number= roundToNearestMultiple($input, 15);

/* 
    Outputs:
      $input= 89 -> $number= 90
      $input= 1869 -> $number= 1875
*/

 

Share this post:
read more

Create a random string with PHP

php-banner

How to create a random string with PHP.

Step 1:

Include the following function somewhere.

function randomstring($length)
{
  $string = "";
  $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  for($i=0;$i<$length;$i++)
  $string.=substr($chars,rand(0,strlen($chars)),1);
  return $string;
}

I’ve only included upper and lower case characters here, but you can add anything to the $chars variable, and they will be included and picked at random.

Usage:

Just send the length of the string you want to return to the function when you call it, and it will return your random string.  So a random 15 character string would be:

$randomString= randomstring(15);

 

Share this post:
read more

How to capitalise the first word of each sentence – PHP

php-banner

So this can be a tricky one.  PHP has some excellent built-in functions for capitalising the first word of a string and capitalising all of the words in a string, but there are no built-in functions (that I’m aware of) that will capitalise the first word of each sentence.  This can be overcome using our old favourites, the regular expressions and preg_replace_callback() function.

$outputString = preg_replace_callback('/([.!?])\s*(\w)/', function ($matches) {
    return strtoupper($matches[1] . ' ' . $matches[2]);
}, ucfirst(strtolower($inputString)));

 

Share this post:
read more

Stop jQuery ignoring the if/else conditions

You may or may not have come across this.  If you are using an AJAX call and have added an if/else statement to the success: parameter, and in particular have bound some actions to an element within those clauses, it can carry on and run the else, even if the if has been satisfied.

Example:

success: function(result) {

            if(result == "success")
            {
                window.location.replace('/somewhere_else');
            }
            else {
                $("#errorMsg").append(result);
            }

        }

This can be avoided if you terminate the jQuery with a false return.

Example:

success: function(result) {

            if(result == "success")
            {
                window.location.replace('/portal');
                return false;
            }
            else {
                $("#errorMsg").append(result);
            }

        }

It will halt the jQuery in its tracks, before it can do something odd.

This is observational behaviour and could well be something that I am doing that is causing this in the first place, so if it is, and somebody would be kind enough to point it out, I would be very obliged.

Share this post:
read more

Centre a form using Bootstrap 4 native controls

That pesky login form that simply refuses to be in the middle.  Not a problem, see the example below:

<div class="row h-75 justify-content-center align-items-center">
        <form>
            <div class="form-group">
                <label for="formGroupExampleInput">Example label</label>
                <input type="text" class="form-control" id="formGroupExampleInput" placeholder="Example input">
            </div>
            <div class="form-group">
                <label for="formGroupExampleInput2">Another label</label>
                <input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Another input">
            </div>
        </form>
    </div>

The h-XXX after the row attribute is the height of the box.  A small number, a higher box.  If this number is set to 100, the form will be centred.

Share this post:
read more

JQuery is() and not() and isNot() :not()

Probably is() as confusing as it sounds.

Example is();

if($(this).is('.disabled){
    // Do something if the element is disabled
}
else {
    // Do something if the element isn't disabled
}

The assumption then is that the not() function is the opposite.  Sadly, this isn’t the case.  The is() function will return a Boolean value (true/false), however, the not() function is a filter and will return a specific set of elements.

So what is the opposite of is()?  It’s the same as PHP [and others], you just add an ! to reverse it:

if(!$(this).is('.disabled){ 
    // Do something if the element isn't disabled 
} else { 
    // Do something if the element is disabled 
}

 

 

Share this post:
read more

Class to add some table functionality to FPDF

php-banner
<?php
require('fpdf.php');

class PDF extends FPDF
{
// Load data
function LoadData($file)
{
    // Read file lines
    $lines = file($file);
    $data = array();
    foreach($lines as $line)
        $data[] = explode(';',trim($line));
    return $data;
}

// Simple table
function BasicTable($header, $data)
{
    // Header
    foreach($header as $col)
        $this->Cell(40,7,$col,1);
    $this->Ln();
    // Data
    foreach($data as $row)
    {
        foreach($row as $col)
            $this->Cell(40,6,$col,1);
        $this->Ln();
    }
}

// Better table
function ImprovedTable($header, $data)
{
    // Column widths
    $w = array(40, 35, 40, 45);
    // Header
    for($i=0;$i<count($header);$i++)
        $this->Cell($w[$i],7,$header[$i],1,0,'C');
    $this->Ln();
    // Data
    foreach($data as $row)
    {
        $this->Cell($w[0],6,$row[0],'LR');
        $this->Cell($w[1],6,$row[1],'LR');
        $this->Cell($w[2],6,number_format($row[2]),'LR',0,'R');
        $this->Cell($w[3],6,number_format($row[3]),'LR',0,'R');
        $this->Ln();
    }
    // Closing line
    $this->Cell(array_sum($w),0,'','T');
}

// Colored table
function FancyTable($header, $data)
{
    // Colors, line width and bold font
    $this->SetFillColor(255,0,0);
    $this->SetTextColor(255);
    $this->SetDrawColor(128,0,0);
    $this->SetLineWidth(.3);
    $this->SetFont('','B');
    // Header
    $w = array(40, 35, 40, 45);
    for($i=0;$i<count($header);$i++)
        $this->Cell($w[$i],7,$header[$i],1,0,'C',true);
    $this->Ln();
    // Color and font restoration
    $this->SetFillColor(224,235,255);
    $this->SetTextColor(0);
    $this->SetFont('');
    // Data
    $fill = false;
    foreach($data as $row)
    {
        $this->Cell($w[0],6,$row[0],'LR',0,'L',$fill);
        $this->Cell($w[1],6,$row[1],'LR',0,'L',$fill);
        $this->Cell($w[2],6,number_format($row[2]),'LR',0,'R',$fill);
        $this->Cell($w[3],6,number_format($row[3]),'LR',0,'R',$fill);
        $this->Ln();
        $fill = !$fill;
    }
    // Closing line
    $this->Cell(array_sum($w),0,'','T');
}
}

$pdf = new PDF();
// Column headings
$header = array('Country', 'Capital', 'Area (sq km)', 'Pop. (thousands)');
// Data loading
$data = $pdf->LoadData('countries.txt');
$pdf->SetFont('Arial','',14);
$pdf->AddPage();
$pdf->BasicTable($header,$data);
$pdf->AddPage();
$pdf->ImprovedTable($header,$data);
$pdf->AddPage();
$pdf->FancyTable($header,$data);
$pdf->Output();
?>

 

Share this post:
read more

Disable and enable buttons (Bootstrap) using a jQuery extension

A nice easy way to disable and re-enable buttons [etc] in Bootstrap with a little extension to the jQuery library.

Add this into the js file, either a custom.js or the main jQuery class file.  Custom being better so it doesn’t get overwriten in the future.

jQuery.fn.extend({
    disable: function (state) {
        return this.each(function () {
            var $this = $(this);
            $this.toggleClass('disabled', state);
        });
    }
});

Then use like this:

$("#button").disable(true);
$("#button").disable(false);

 

 

 

Share this post:
read more

Bootstrap modal background doesn’t disappear when modal closes

This can happen in certain circumstances for a lot of reasons.  If you need a quick and dirty hack to get everything shut down (modal wise) in full, you can use:

$('#your-modal-id').modal('hide');
$('body').removeClass('modal-open');
$('.modal-backdrop').remove();

It’s overkill, but effective.

Share this post:
read more

Only allow numbers to be entered in an HTML form text field

Sometimes, if you are adding say, a phone number into an input field, you don’t want people to enter letters.  This snippet contains a handy little regex to remove any non-number from an input as the user types.  It’s not foolproof, but it does the job.

Nice simple addition to forms to only allow letters in a text input field:

$("#yourInput").keyup(function()
    {
        if (/D/g.test(this.value))
        {
            // Remove the non-digits from the input
            this.value = this.value.replace(/D/g, '');
        }
    });

UPDATE (2018)

Given that this was a lazy post back when I wrote it, I’ve added a slightly updated version that will look for a change, and other inputs as well.  A few more event listeners will cover some of the users who may like to paste things into the box.

Remember, making forms look pretty before they are submitted it great, but it doesn’t replace proper server-side validation of the input at the other end.  If you are using a database, don’t just sanitise, prepare.

$("#yourInput").on("keyup paste change", function()) 
{ 
  if (/D/g.test(this.value)) 
  { 
    this.value = this.value.replace(/D/g, ''); 
  } 
});

 

Share this post:
read more

1 2 3 4 5 6