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"
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.
$argv — Array of arguments passed to script.
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.
$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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With