Ternary Operators in PHP

A   ternary operator is a different way to layout a simple if statement. Let’s take a look at one and then break it down. We’ll just use a simple check to see if a GET parameter is set and not empty, if it is we will default to the word John, otherwise use the value that was set as the GET parameter.

$name = (!empty($_GET['name'])? $_GET['name'] : 'John');

This might look complex to begin with but there are three sections to a ternary operator:

  1. The conditional !empty($_GET['name'])
  2. The true result $_GET['name']
  3. The false result 'John'

The ternary operator will return either the true or false conditional, and therefore it will be assigned to $name. If we write this as a normal if statement we’d have one of the following:

if(!empty($_GET['name'])){
    $name = $_GET['name'];
}else{
    $name = 'John';
}

// Or

$name = 'John';
if(!empty($_GET['name'])){
    $name = $_GET['name'];
}

The two above and the ternary operator will all end up with $name having something assigned to it.

Nesting

While not advisable, it is possible to nest ternary operators within each other much like you would with standard if statements, or to form a long string of if...else if...else if...else statements.

Ternary operators can be very helpful and clean up code, but don’t over complicate them otherwise your code might become inundated with large amounts of complex rediculousness that will get you hunted down by a violent psychopath.

Class Autoloading

To make use of a class file, you have to ensure that the class you’re using is available within the page that you’re using it. In most cases this will be as easy as you just including the PHP file that contains the class.

But what if we have a very large number of classes that we could potentially use within one or many sections of our code? Well, we could include all of them within a common header file, or only include the ones that we know that we’re going to use on that page. However, we then need to remember to include new classes whenever we want to use a different one etc.

So instead of including classes that might not get used, or we might remove later, we can employ class autoloading. When we autoload classes we can write what will happen – this might be to just throw an error to let us know that we’ve not included the class file, or, as in most cases, we make the function include the file that we need.

The Code

Here we’ll be using the PHP function spl_autoload_register(), we’ll only be interested in the first parameter, but there are two others that you can define if you wanted the function to behave differently. I’ll jump straight into how to use it:

function loadMyClass($class){
    echo 'We are loading class: ' . $class;
    include_once('classes/' . $class . '.inc.php');
    echo 'Class loaded.';
}

spl_autoload_register('loadMyClass');

This will pass the name of the class that we’re trying to load as the first parameter of the function that we specified. As of PHP 5.3.0 we are able to use anonymous functions, basically a function thas has no name:

spl_autoload_register(function ($class){
    echo 'We are loading class: ' . $class;
    include_once('classes/' . $class . '.inc.php');
    echo 'Class loaded.';
});

Which will work exactly the same as the method of implementation above. So now in future, we don’t need to include the class files that we’ll be using as this function will run if the class is undefined, include the class and then the instantiation will be called.

Dynamic Variables

Sometimes we want to be able to dynmically define a variable, or refer to a variable based on a user’s input. Let’s start with this code:

$myname = 'Michael';
$yourname = 'Ben';
if($_GET['whatname'] == 'your'){
    echo $yourname;
}else if($_GET['whatname'] == 'my'){
    echo $myname;
}else{
    echo 'No Name';
}

To use the value of a variable to then form another variable we use double dollar signs $$ so for example we could do $who = 'myname'; then echo $$who. This will echo out the value of $myname.

Break it down like this (exemplary code, not actual working code):

$who = 'myname';
$$who = $'myname';
$$who = $myname;
echo $$who; // would return 'Michael'

In reference to the code above we could look to use something along the lines of the following for very dynamically defined variables:

$who = $_GET['whatname'] . 'name';
if(isset($$who)){
    echo $$who;
}else{
    echo 'No Name';
}

As with ternary operators, you should use these loosely, as in most situations there’s not much need for them, but you will most probably find some crazy-ninja somewhere who uses this notation.

Referencing

Passing variables by reference, is a way to pass variables into functions so that the function can alter the original variable without having to return anything or define it as global etc. A function parameter that is going to be passed in as a reference is preceeded by an ampersand (&). Let’s go with an example:

function lowercase(&$string){
    $string = strtolower($string);
}

$name = 'STEPHEN';
lowercase($name);
echo $name; // returns stephen

What you can see is that where we’ve called the lowercase() method and passed in $name, the function has altered the actual string that we passed in, as within the function $string becomes $name.

There are advantages of using references, for example you don’t have to return anything from the function, nor do you have to look to define them as globally accessible.

Arrays

References are super awesome when you use them with arrays. Let’s say we have a function that sets the first item in any array to potato – because you know, it’ll be the most helpful function ever:

function potatoArray(&$array){
    $array[0] = 'potato';
}

$nonpotato = array(
    'john',
    'andrew',
    'cheese'
);

potatoArray($nonpotato);

print_r($nonpotato); // This will now have changed 'john' to 'potato'

References are very powerful things, and could be used extensively. You’ll find them used with the array_walk() method other some other array methods that PHP have.

Relative Time Calculation

Everywhere you look people love their relative times, they’re on Facebook, they’re in most Twitter apps and they’re here on Codular. Codular isn’t too fussed about the specific time of when an action was made and so we have come up with a special class with handle the relative date for us.

We define a list of the days that exist, and then do some logic to find out what to display. We firstly check if it’s today or yesterday, obviously returning the respective term. We then look to see if the date falls in the last 7 days (less than 8 days), this is so that we can display last Monday, last Sunday etc. But obviously the ‘Last’ prefix can only apply to one week.

Our method takes a second parameter with is a fallback format, this is the format that we use when the date falls out of the ‘Last’ date range. The first parameter is a simple UNIX timestamp.

<?php

class TimeClass {

    private static $days = array(
        'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'
    );

    /**
     * relativeTime()
     * @param int $time
     * @param string $format
     */
    public static function relative($time, $format = 'jS F Y'){
        if(date('d/m/Y', $time) === date('d/m/Y')){
            return 'Today';
        }else if(date('d/m/Y', $time) === date('d/m/Y', time() - 3600 * 24)){
            return 'Yesterday';
        }else if((time() - $time) < 3600 * 24 * 8){
            return 'Last ' . self::$days[date('w', $time)];
        }else{
            return date($format, $time);
        }

    }

}

Usage would be as simple as doing:

echo TimeClass:relative(time());

That will always output Today as we are using the current timestamp.

Relative date calculations can be pretty smple, another that is commonly used is to round to the nearest multiple of a time frame – ie days, weeks, months years etc. Below is a quick function to finish off with that will do exactly that up to 10 years in time then fall back to a date:

<?php

function relativeTime($timestamp, $format = 'Y-m-d H:i'){
    $dif = time() - $timestamp;

    $dateArray = array(
        "second" => 60,     // 60 seconds in 1 minute
        "minute" => 60,     // 60 minutes in 1 hour
        "hour" => 24,       // 24 hours in 1 day
        "day" => 7,         // 7 days in 1 week
        "week" => 4,        // 4 weeks in 1 month
        "month" => 12,      // 12 months in 1 year
        "year" => 10        // Up to 10 years
    );

    foreach($dateArray as $key => $item){
        if($dif < $item)
            return $dif . ' ' . $key . ($dif == 1? '' : 's') . ' ago';
        $dif = round($dif/$item);
    }
    return date($format, $timestamp);
}
Advertisements

Keyboard Shortcuts for Microsoft Excel

Ctrl + O Open existing file
Ctrl + N Create new workbook
Ctrl + S Save current workbook
Ctrl + F4 Close current workbook
Ctrl + Z Undo last action
Ctrl + Y Redo last action
Ctrl + C Copy selection
Ctrl + X Cut selection
Ctrl + V Paste selction
Ctrl + P Print (displays print menu and options)
Ctrl + S Save file
F12 Save file as

Entering Data

 

Enter Complete cell data entry and move to cell below.
Ctrl + Shift + Enter Enter/create array formula
Alt + Enter Start new line in the same cell.
Ctrl + Enter Fill selected cell range with current entry.
Shift + Enter Complete cell data entry and move to cell directly above current cell.
Tab Complete cell data entry and move to the cell to the right.
Shift + Tab Complete cell data entry and move to the cell to the left.
Esc Cancel a cell entry and go back to what was there before.
Arrow Keys Move one cell left, right, up, or down.
Home Move to the first column (A).
F4 / Ctrl + Y Repeat last action.
Ctrl + Shift + F3 Create names for row and column labels.
Ctrl + D Fill down.
Ctrl + R Fill to the right.
Ctrl + F3 Define a name for a cell or range of cells.
Ctrl + K Insert a hyperlink.
Enter (after insertion of hyperlink) Activate a hyperlink.
Ctrl + ; Enter the current date.
Ctrl + Shift + : Enter the current time.
Alt + Down Arrow Display a drop-down list of the values in the current column of a list.
Ctrl + Z Undo the last action.
Alt + F8 Displays macro dialog box.
Alt + F11 Displays the visual basic editor.
Ctrl + F11 Inserts an Excel 4.0 macro sheet.

Edit Data

 

F2 Edit highlighted cell – cursor is at the end of cell contents.
Alt + Enter Start a new line in the same cell.
Backspace When cell is highlighted, deletes cells contents.
Delete Deletes cells contents if cell is highlighted.
Ctrl + Delete Deletes text to the end of the line.
F7 Runs spell-check.
Shift + F2 Inserts and edits comments.
Enter Completes cell entry and moves to cell below.
Ctrl + Z Undo last action.
Esc Cancel a cell entry, previous contents are restored.
Ctrl + Shift + Z When the autocorrect smart tags is displayed, undo or redo the last automatic correction.
Ctrl + C + Ctrl + C Displays the clipboard (where copied items are).
Ctrl + – Removes/deletes selected cells from the sheet.
Ctrl + Shift + “+” Inserts blank cells.

Format Data

 

Alt + Display style dialog box.
Ctrl + 1 Display format cells dialog box.
Shift + Spacebar Highlight row
Ctrl + Spacebar Highlight column
Ctrl + Shift + ~ Apply the ‘general number’ format to selected cells.
Ctrl + Shift + $ Apply the ‘currency number’ format with two decimal places and negative numbers showing in parentheses to selected cells.
Ctrl + Shift + % Apply the ‘percentage’ format with no decimal places to selected cells.
Ctrl + Shift + ^ Apply the ‘exponential number’ format with two decimal places to selected cells.
Ctrl + Shift + # Apply the ‘date’ format with the day, month, and year to selected cells.
Ctrl + Shift + @ Apply the ‘time’ format with the hour, minute, and AM or PM to selected cells.
Ctrl + Shift +! Apply the ‘number’ format with two decimal places, thousands seperator, and minus sign for negative numbers to selected cells.
Ctrl + B Apply/remove bold format to selected cells.
Ctrl + I Apply/remove italic format to selected cells.
Ctrl + U Apply/remove underline to selected cells.
Ctrl + 5 Apply or remove ‘strikethrough’ to selected cells.
Ctrl + 8 Displays or hides the outline of symbols.
Ctrl + 9 Hide row.
Ctrl + Shift + 9 Unhide row.
Ctrl + Shift + ( Unhide any hidden rows within the selection.
Ctrl + 0 Hide the selected columns.
Ctrl + Shift + ) Unhide any columns within the selection.
Ctrl + Shift + & Apply the ‘border outline’ to selcted cells.
Ctrl + Shift + _ Remove the ‘border outline’ from selected cells.
Alt + Shift + Right Arrow Groups selected rows or columns.
Alt + Shift + Left Arrow Ungroups selected rows or columns.

Macros

 

Alt + F8 Displays macro dialog box.
Alt + F11 Displays the visual basic editor.
Ctrl + F11 Inserts an Excel 4.0 macro sheet.

Scale Data for Printing in Excel – Fit more onto a Printed Page

This tip shows you how to fit more Excel data onto a page for printing. This does not change the size, shape, or look of the data in the actual Excel spreadsheet. In other words, the spreadsheet will look exactly the same as before in Excel, but it will be smaller when it is printed. This effectively allows you to shrink the Excel data on the printed page.

This is a very useful feature to use when you are trying to format your Excel workbooks for printing and want a certain amount of information to appear on a printed page.

Steps to fit more data onto a printed page in Excel:

  1. Open the “Page Setup” window in Excel.
    • Excel 2003 (or Earlier): File > Page Setup
    • Excel 2007: Page Layout tab > Page Setup box > button in bottom right-hand corner of the box.
  2. Page tab.
  3. Scaling section – Select “Adjust to:.”
  4. Change the percentage box from 100% higher or lower in order to better fit the data onto the printed page.
  5. Click the “Print Preview” button at the bottom of the window.
  6. Verify that the page looks like you need it to and either close the Print Preview window or go back to step 4 to adjust the scaling.

Steps to scale workbooks for printing in Excel in pictures:

    1. Excel 2003 (or Earlier)

    Excel 2003 Page Setup

      1. Excel 2007 (or Earlier)

      Excel 2007 Page Setup

        1. Page Setup Window

        Excel 2007 Page Setup Adjust Window

          1. Page Setup > Print Preview

          Excel 2007 Page Setup Print Preview

          Remove Gridlines in Excel 2007

          Excel 2007 you can quickly remove the gridlines that appear within the Excel worksheet. This allows you to view the worksheet without any lines in it. You won’t see the outline of any cells and this may not seem like a good idea. However, this allows you to make really clean looking spreadsheets in Excel and allows you to put focus on certain elements within the spreadsheet. This is especially helpful when creating forms in Excel; when doing this you don’t need or want extra gridlines within the spreadsheet.

           

          Remove or Add Gridlines in Excel 2007:

           

          View tab > Show/Hide box > Un-check the Gridlines check box

           

          Remove Gridlines in Excel 2007

           Sales Report with Gridlines:

            Sales Report with Gridlines

           

          Sales Report without Gridlines:

           

           

          Sales Report without Gridlines

          Sort Data Alphabetically or Numerically in Excel 2007

          Sort Data Alphabetically or Numerically in Excel 2007

          This Excel tip shows you how to Sort Data Alphabetically and Numerically in Excel 2007. This is a great feature to use when analyzing and organizing large sets of data and it can help to make sense out of all of that data.

          The sort feature in Excel allows you to very quickly sort any data set alphabetically and also numerically. That means A-Z, Z-A, 1-10, and 10-1. Basically, this is sorting data forwards and backwards.

          Steps to Sort Data Alphabetically or Numerically in Excel 2007:

          1. Select a cell within the data set which you would like to sort.
          2. Go to the Data tab in the ribbon menu.
          3. Sort & Filter box.
          4. Click “AZ” to put the list or data set in alphabetical order or in numerical ascending order so that the lowest values are at the top.
          5. OR Click “ZA” to put the list or data set in reverse alphabetical order or in numerical descending order so that the highest values are at the top of the list.

          Note: You may or may not have headers for your data. Excel doesn’t care if you have headers but it will try to determine on its own whether or not your data does contain headers. Also, this method is a very quick way to sort your data alphabetically or numerically. If you need to you can perform more advanced sorting methods in Excel by clicking the button to the right of the two small sort buttons in the ribbon menu.

           

          Location of Sort on the Excel 2007 Ribbon Menu:

          Sort Location Excel 2007 Ribbon Menu

           

          Excel Worksheet Before Sort:

          Excel Worksheet Before Sort

           

          Excel Worksheet Before Sort:

          Excel Worksheet After Sort

          NOW() – Display The Current Time in Excel

          NOW() – Display The Current Time in Excel

          This Excel tip will show you how to display the current time within any Excel spreadsheet. This is a useful function if you need to let the user know just how much time left the have to do something or simply to inform them of the current time. Examples include creating forms with Excel, reports with Excel, presentations with Excel, etc.

          The standard NOW() function will return the current date formatted as MM/DD/YYYY and the time formatted as hh:mm. This means that it does take a little bit of formatting to get this function to display the time without also displaying the date.

          Function to Display the Current Time in Excel:

           =NOW()

          Steps to Display the Current Time in Microsoft Excel:

          1. Type “=NOW()” into the cell which should display the current time and hit the enter key.
          2. Right-click the cell in which you just entered the above formula and click “Format Cells….”
          3. Navigate to the “Number” tab; by default, you should already be on that tab.
          4. Make sure you are in the “Custom” category along the left side of the window and then in the right side of the same window select “hh:mm” or “hh:mm:ss” to display the time with or without also displaying the seconds.
            • Note: The “hh:mm” and “hh:mm:ss” options should be right above the default selection option.

           View of the Format Cells Window:

          Format Cells Window Excel 2007

          MODE() – Find Most Repeated Value in a List in Excel

          MODE() – Find Most Repeated Value in a List in Excel

          The MODE() function in Excel allows you to quickly find the most repeated or frequently occuring value within a list or range of data. This allows you to quickly analyze a series of data to do things like finding the highest sales amount for a quarter or the cost of the most expensive part in a project, and so much more.

          Note: Arguments for the MODE() function in Excel can be numbers, names, arrays, or other references that contain numbers. Also, any argument in the MODE() function that is text that can’t be turned into a number or that throw errors will return an error for the MODE() function. If there are no duplicate values in the list, which means there can be no value repeated more than another, this function will return an error in Excel.

          Syntax for the MODE() function in Excel:

           

          MODE(number1, number2, …)

           

          Sample:

          MODE() Function in Excel