Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking command line argument in PHP

Tags:

php

I want to pass two different arguments to my script and based on the sent argument, I need my script does something.But I don't know how to define my conditional statement.

To be more precise, I want my script does searching when I pass "search" argument and alternatively showing the result when I pass "show" argument.

Here is my code:

if ($argc > 1) {
  if ($argv[0] == 'show') {
    for ($i = 0; $i <= $argv[2]; $i++) {
      //do something
    }
  }
  elseif($argv[0] == 'search') {
    //do something
  }
} else {
  echo "no argument passed\n";
}

The "IF" statement is not checking my passing argument whether it is "search" or "show"

like image 920
Babak Khoramdin Avatar asked Apr 14 '13 11:04

Babak Khoramdin


People also ask

How do I pass a command line argument in PHP?

To pass command line arguments to the script, we simply put them right after the script name like so... Note that the 0th argument is the name of the PHP script that is run. The rest of the array are the values passed in on the command line. The values are accessed via the $argv array.

What is $argv in PHP?

$argv — Array of arguments passed to script.

What is CLI PHP?

PHP's Command Line Interface (CLI) allows you to execute PHP scripts when logged in to your server through SSH. ServerPilot installs multiple versions of PHP on your server so there are multiple PHP executables available to run.


1 Answers

$argv[0] is the name of the script, that's why your code doesn't work.

If I have a file script.php:

<?php
if ($argc > 1) {
  if ($argv[1] == 'show') {
    for ($i = 0; $i <= $argv[2]; $i++) {
      print "show passed\n";
    }
  }
  elseif($argv[1] == 'search') {
    print "search passed";
  }
} else {
  echo "no argument passed\n";
}

Testing gives:

$php script.php

no argument passed

$php script.php search

search passed

$php script.php show 2

show passed
show passed
show passed
like image 142
user4035 Avatar answered Sep 30 '22 08:09

user4035