PHP Variable Validation

Judge a variable’s type

To get the type of a variable, use gettype() function.

It returns the type as string. Returned values are:

  • “boolean”
  • “integer”
  • “double” (for historical reasons “double” is returned in case of a float, and not simply “float”)
  • “string”
  • “array”
  • “object”
  • “resource”
  • “resource (closed)” as of PHP 7.2.0
  • “NULL”
  • “unknown type”


$t = gettype( True ); // "boolean"
$t = gettype( 1 );    // "integer"
$t = gettype( 1.1 );  // "double"
$t = gettype( NAN );  // "double"
$t = gettype( 'a' );  // "string"
$t = gettype( [1] );  // "array"
$t = gettype( $foo ); // "NULL", notice will ge given because $foo is not defined.
$t = gettype( new stdClass );   // "object"

There are a series of is_* functions that can be used to determine whether a variable is a certain kind of “type”. These functions accept an variable and return a boolean to indicate the is_* checking is true or false.

PHP’s ten primitive types (including one pseudo-type iterable) checking.

Other “type” checking.

  • is_scalar(), find whether a variable is a scalar. Only types boolean, integer, float, string are scalar.
  • is_numeric(), find whether a variable is a number or a numeric string.
  • is_countable(), verify that the contents of a variable is an array or an object implementing Countable.
  • is_finite(), check whether a float value is a legal finite number on this platform. It accepts a float parameter.
  • is_infinite(), check whether a float value is infinite on this platform. It returns TRUE if a variable is infinite (positive or negative), like the result of log(0) or any value too big to fit into a float on this platform.

These are alias of existing is_* functions.

  • is_integer(), alias of is_int().
  • is_long(), alias of is_int().
  • is_double(), alias of is_float().
  • is_real(), alias of is_float().


// is_numeric()
$r = is_numeric( '12' );   // true
$r = is_numeric( '09' );   // true
$r = is_numeric( "10e0" ); // true
$r = is_numeric( "0x41" ); // false

// is_iterable()
$r = is_iterable( [1, 2, 3] );                       // true
$r = is_iterable( new ArrayIterator( [1, 2, 3] ) );  // true
$r = is_iterable( ( function (){ yield 1; } ) () );  // true
$r = is_iterable( new stdClass() );                  // false

// is_countable()
$r = is_countable( [1, 2, 3] );                 // true
$r = is_countable( ArrayIterator(['a', 'b' ) ); // true
$r = is_countable( new ArrayIterator() );       // true
$r = is_countable( new stdClass() );            // false

// is_finite(), is_infinite()
$r = is_finite( 1.0 / 3); // true
$f = acos( 2 );
$r = is_finite( $f );     // false
$r = is_infinite( $f );   // false
$r = is_nan( $f );        // true

// is_callable()

// prototype: is_callable ( mixed $var [, bool $syntax_only = FALSE [, string &$callable_name ]] ) : bool

function foo() {}
$r = is_callable( 'foo' );    // true

$func = function () {};
$r = is_callable( $func );    // true

class Foo {
    public function __construct() {}
    public function foo() {}

$obj = new Foo();
$class_func = array( $obj, 'foo' );
$r = is_callable( $class_func );                   // true

// Note in PHP 5.3.0 is_callable() reports constructors as not being callable.
$r = is_callable( array( 'Foo', '__construct' ) ); // false
$r = is_callable( array( 'Foo', 'foo' ) );         // false

// The second parameter $syntax_only is false by default.
// If it is set to ture, it only reject simple variables that are not strings,
// or an array that does not have a valid structure to be used as a callback.
$r = is_callable( array( 'Foo', '__construct' ), true );   // true
$r = is_callable( array( 'Foo', 'foo' ), true );           // true

Validate a variable’a value

Before use a variable, it is a good idea to check whether it is properly initialized. is_set() and empty() will help you.

  • isset(), determine whether a variable is declared and is different than NULL.
  • empty(), determine whether a variable is empty. A variable is considered empty if:
    • it does not exist.
    • its value equals FALSE. A variable is considered FALSE:
    • boolean FALSE
    • integer 0 and -0
    • float 0.0 and -0.0
    • empty string
    • empty array
    • NULL
    • object SimpleXML created from empty tags

You may notice that is_null() may help as well. But note that if it takes an undefined parameter, you will have notice information,the other two functions will not bring notice. Therefor use isset() first to make sure a variable has been set a value then check the type using is_*() functions.

  • is_null(), determine whether a variable is NULL. A variable is considered to be NULL:
    • it has been assigned the constant NULL.
    • it has not been set to any value yet.
    • it has been unset with function unset().

Relationships between isset(), empty() and is_null(): a variable is true either in isset() or is_null(). empty() contains is_null and part of isset().

// --------isset()

$a = 1;
$b = 'hello';
var_dump( isset( $a ) ); // bool(true)

// isset() can take more than one parameters.
// It returns TRUE only if all of the parameters are considered set.
var_dump( isset( $a, $b, $c ) ); // bool(false)
var_dump( isset( $c ) );         // bool(false)

// --------empty()

empty( $c ); // bool(true)

// --------is_null()

var_dump( is_null( $c ) ); // bool(false), but it will give notice for $f is undefined.

Test/Debug a variable’s type and value

To test or debug a variable’s type and value, you may use var_dump() function. This function displays structured information about one or more expressions that includes its type and value.

$a = 1.1;
var_dump( $a );
/* output:

$b = true;
var_dump( $a, $b ); // display morn than one expressions
/* output:

$c = array (
    'a' => 'Apple',
    'color' => array ( 'Red', 'Green', 'Blue' )
var_dump( $c );
/* ouput:
array(3) {
  array(1) {
    string(5) "Apple"
  array(3) {
    string(3) "Red"
    string(5) "Green"
    string(4) "Blue"

Check a string’s value with var_dump()

Note if you dump information of a string with var_dump(), the escape characters will be interpreted as printed.

$a = 'I'm a character.';
var_dump( $a );
/* output
string(16) "I'm a character."

$b = "First line \rn Second line \rn";
var_dump( $b );
/* output
string(32) "First line .
 Second line .

In addition to var_dump(), you can also use print_r() and var_export(). Compared to var_dump():

  • print_r() outputs or returns value about a variable in a way that’s readable by humans.
  • var_export() outputs or returns a parsable string representation of a variable. The returned representation is a valid PHP code.
// print_r prototype:
// print_r( mixed $expression [, bool $return = FALSE ] ) : mixed

print_r( $c );
/* output:
    [0] => 1
    [a] => Array
            [0] => apple

    [color] => Array
            [0] => Red
            [1] => Green
            [2] => Blue


print_r( $c, true ); // It will return the information rather than output it.

// var_export prototype:
// var_export ( mixed $expression [, bool $return = FALSE ] ) : mixed

var_export( $c );
/* output:
array (
  0 => 1,
  'a' =>
  array (
    0 => 'apple',
  'color' =>
  array (
    0 => 'Red',
    1 => 'Green',
    2 => 'Blue',

$v = var_export( $c, true );
    // It will return the variable representation rather than output it.
    // Now $v is a valid piece of code which represted in string as showed above.
eval( '$d' . $v . ';' );
var_dump( $d );
/* output:
array(3) {
  array(1) {
    string(5) "apple"
  array(3) {
    string(3) "Red"
    string(5) "Green"
    string(4) "Blue"




  • Partial clone

    How to clone only part of commits of a huge repository



  • Stash changes

    How to save changes temporally, apply changes, list stashes, delete a stash?




  • Remote management

    How to add a remote, delete a remote, change the URL of a remote, etc.


  • Differences

    How to check differences between working tree, index, a specific commit?




  • Check log

    How to view the last several commits, search the commit history with string, list the commits graphically, check which commit changed a string, etc.

Useful git commands with examples

Here it gives some useful commands with examples. These commands cover most of the usage scenarios in your daily use of git. With them, your experience with git will becomes much more easier.

Here are commands covered in this article.
– git config
– Config common used command alias
– Config editorConfig default commit template
– Config Beyond Compare 4 as your difftool
– Add .gitignore to ignore files
– git stash
– git reset
– git revert
– git cherry-pick
– git diff
– git difftoo
– git format-patch
– git show
– git log
– git grep

git config

git config can be used to get and set options in a repository or globally. Below are several useful examples to set your repository.

Config common used command aliases

It’s a good practice to config aliases for your common used commands to type more quickly.

# Use alias "git co" instead of "git checkout"
$ git config --global checkout

# Use alias "git st" instead of "git status"
$ git config --global status

# Set "git last" as a alias to view the last commit
$ git config --global alias.last 'log -1 --oneline HEAD'

# Set "git unstage" as a alias to undo the changes in index
$ git config --global alias.unstage 'reset HEAD --''

Config editor

# Config vim as your editor
$ git config --global core.editor vim

# Config notepad++ as your editor
$ git config --global core.editor "'C:/Program Files (x86)/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"

See more tools as text editor in git.

Config default commit template

Step 1: write your own git commit template file. Such as file ~/.gitmessage and put below contents:

Subject line (try to keep under 50 characters)

Multi-line description of commit to explain
what, why and how this change is being made
(try to limit each line under 72 Characters)

Provide ticket numbers or links to other relevant resource
[Ticket: #53]

Step 2: config it as your commit template:

# Config a custom commit template
$ git config --global commit.template ~/.gitmessage

See setting commit template for how to write ignoring rules.

Config Beyond Compare 4 as your difftool

# Config Beyond Compare 4 as difftool

$ git config --global diff.tool bc4
$ git config --global difftool.prompt false
# Note: set parameters for Beyond Compare tool
$ git config --global difftool.bc4.cmd '"C:Program FilesBeyond Compare 4BCompare.exe" "$LOCAL" "$REMOTE"'

Add .gitignore to ignore files

In fact, setting up files to ignore does not use git config command.

To set up your.gitignore file:

Step 1: create a file named .gitignore in the root of your git repository. Put your ignoring rule in the file, below is an example:

# ignore all .class files

# ignore all .log files

# ignore build folder in the root directory

Step 2: commit .gitignore to make it take effect:

$ git add .gitignore
$ git commit

See ignoring files in git for more.

git stash

git stash can be used to save changes away temporally (it store them on a stack) if you don’t want to commit yet. It is very useful when you need to pause the task in progress and checkout to another branch for a more emergent one. Below is your work flow with git stash:

# Stash your work on current branch, let's call it develop
$ git stash

# Checkout to topic branch for the emergent task
$ git checkout topic

# After you finish your work, execute add and commit
$ git add .
$ git commit

# Checkout back to the prior branch
$ git checkout develop

# Apply changes you have stashed before
$ git stash apply

# Continue your work on develop branch

Other examples:

# Apply the top stash on the stack
# Note: staged changes in the stash are not restaged
# and stash is removed from stack.
$ git stash apply stash@{0}

# Revert working tree and staging area
$ git stash apply --index

# Repplay a stash and remove it from stack
$ git stash pop stash@{0}

See stashing changes for more usages.

git reset

git reset can be used to reset current HEAD to point to another commit. By using different options, you can control the reset degree, such as commit, index, working tree.


# Discard the last commit.
# The commit's modifications in working tree are kept.
$ git reset HEAD~

# Discard the last commit.
# The commit's modifications in staging area are kept.
$ git reset --soft HEAD~

# Discard the last commit.
# The commit's modifications in working tree are not kept.
$ git reset --hard HEAD~

git revert

git revert can be used to revert a commit that has been pushed to remote repository. This command does not change the history but makes a new commit which reverses the modifications.

# Undo a commit that has been pushed.
$ git revert -m 1 HEAD

See more about undoing operations.

git cherry-pick

git cherry-pick applies changes introduced in some specified commits. With this command, you can make a new commit with the changes got from another commit :


# Apply the changes introduced by commit 95f2137 and
# create a new commit with the change
$ git cherry-pick 95f2137

# Apply the changes introduced by tip commit of develop branch
$ git cherry-pick develop

# Apply the changes introduced by tip commit of develop branch
# in working tree and staging area, but not commit the changes.
$ git cherry-pick --no-commit develop

See more examples on copying changes from another commit.

git diff

git diff shows difference between commits, staging area and working tree. Its output can also be used to generate a patch.


# Difference between HEAD's parent and HEAD
$ git diff HEAD~ HEAD

# Difference between HEAD's parent and HEAD for index.php
$ git diff HEAD~ HEAD -- ./index.php

# Difference between working tree and HEAD
$ git diff HEAD

# Difference between staging area and HEAD
$ git diff --cached HEAD

# Create a patch from difference
$ git diff HEAD > patch-issue-53.patch

# Apply a patch generated by git diff output
$ git apply -v atch-issue-53.patch

See showing differences for more examples.

git difftool

git difftool shows difference in a visual tool (see set beycond compare as your difftool). It accepts the same options with git diff.


# Difference between HEAD's parent and HEAD
$ git difftool HEAD~ HEAD

# Difference of index.php between working tree and HEAD
# Note: if there is no difference, nothing is output.
$ git difftool HEAD~ HEAD -- index.php

See showing differences for more examples.

git format-patch

git format-patch generates patches containing submit information which can be used to email submission.

# Create patchs for commits since  to the current branch tip commit
# Note: the specified commit is not included
$ git format-patch 


# Create a patch for the commit HEAD
$ git format-patch HEAD~

# Create patches for commits HEAD~2, HEAD~, HEAD
$ git format-patch HEAD~3

# Create patches for a range of commits: HEAD~ and HEAD
# Note: it prepares each commit with its patch in one file per commit.
git format-patch HEAD~2..HEAD

# Apply a patch created using format-patch
$ git am 0001.patch

git show

git show can be used to show content of objects like a commit, a stash, etc.


# Show contents of asset/css/style.css in commit HEAD.
$ git show HEAD:asset/css/style.css

# Show changed files in commit HEAD
$ git show --name-only HEAD

# Show content of the top stash
$ git stash show stash@{0}

git log

git log can be used to view and search the commit history.


# Show commit history in short format with one log in one line
$ git log --oneline

# Show only the last two commit logs
$ git log -2

# Show commit logs that are made after 2018-12-01
$ git log --after=2018-12-01

# Show only those commits that add or remove string of "update_post_meta"
$ git log -S update_post_meta

# Show only commits made by john
$ git log --author john

# Show all commits of branches in a graph structure
$ git log --all --graph --oneline --decorate

See more about viewing git history.

git grep

git grep is highly useful when you need to do a search in your git repository.


# Grep "Device is HD capable" in .xml files of current directory
$ git grep 'Device is HD capable' -- './*.xml'

Tips: By adding limit arguments (like path and file extensions), you can highly reduce the running time of git grep command.

git tag

git-tag creates, list and delete tags.

A tag can be a lightweight tag (it contains only a tag name) or an annotated tag (except a tag name, it also contains the author name, email, date and a tag message).


# ----------------Create

# Create a lightweight tag "v1.0" for HEAD.
$ git tag v1.0

# Create a lightweight tag "v1.0" for a spicific commit "06d49a9"
$ git tag v1.0 06d49a9

# Create an annotated tag with -a option and -m option
$ git tag -a v1.0 -m "Formal version v1.0"

# ----------------Push
# Push a tag with name "v1.0" to remote
$ git push v1.0

# Push all tags to remote
$ git push --tags

# ----------------List
# List all tags
$ git tag

# List tags that matches a pattern
$ git tag -l "v1.0*"

# ----------------Delete
# Delete a tag with name "v1.0"
$ git tag -d v1.0

See more about tags management.