Rahul's Tech Blog

Growth Hacking, Just Hacking or No hacking !!!

How to take argument in PHP CLI script

Suppose you are writing a PHP CLI script and you need to take an argument from command line, how would you do it ?

Here is how:
Following is a sample program to take a string as argument and reverse it.

  // $argc contains number of argument sent. Name of the string is always first argument
  // So check that total number of argument should not be less than or equals to 1
  if($argc <= 1) {
    // Assuming script is saved a reverse.php
    echo "Invalid usage. Syntax: php reverse.php string";

  // $argv is an array which contains all the argument
  // $argv[0] contains name of the script being executed
  // $argv[1] will contain first argument
  // $argv[2] will contain second argument and so on
  $string = $argv[1];

  // Return reverse string
  echo strrev($string);