Checking command line argument in PHP
php
Solution
`$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
Problem
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"