user1658435
user1658435

Reputation: 574

Dealing with argc and argv

I wrote the code as follows:

<?php
array_shift($argv);
$taskid=$argv[0];
$file1=file_get_contents($argv[1]);
$file2=fopen($argv[2],"w");
echo $taskid."\n".$file1."\n".$file2."\n";
?>

I execute this program as php myfile.php 1 1.txt 2.txt Where 1 is the taskid, 1.txt is the input file and 2.txt is the output file. I want to modify this program in such a way that it runs even though I don't pass any arguments that is like php myfile.php should run. I want to place an if condition for that. I worked with the conditions like if(*argv<=1) and if(argc==NULL) etc., but none of them are working.

I need a perfect condition that checks if no arguments are passed then my program should show a user friendly message.

Can someone help me??

Upvotes: 2

Views: 6480

Answers (2)

m4t1t0
m4t1t0

Reputation: 5721

Try this:

<?php
array_shift($argv);

if (empty($argv) || count($argv) != 3) {
  echo "Incorrect number of arguments\n";
}
else {
  $taskid = $argv[0];
  $file1 = file_get_contents($argv[1]);
  $file2 = fopen($argv[2],"w");
  echo $taskid . "\n" . $file1 . "\n" . $file2 . "\n";
}

Upvotes: 2

xdazz
xdazz

Reputation: 160833

if ($argc !== 4) {
  // show message 

Upvotes: 5

Related Questions