1

I try to get parameters and run php script from terminal. If one of the parameters is not exists, I want to thrown an exception. I used getopt function. But I could not figure out how to thrown exception. And when I call the script

php myscript.php --file: file1.csv --unique-combinations: file2.csv

it's not working.

<?php
$files = getopt("file:unique-combinations:");

if(!files["file"]) {
    echo "Please provide a CSV file with parameter file";
} else if(!files["unique-combinations"]) {
    echo "Please provide a file name to save unique combinations with parameter unique-combinations";
} else {
    $datas = array_count_values(file(files["file"]));
    $fp = fopen(files["unique-combinations"], 'w');

    foreach($datas as $data => $value) {
        fputcsv($fp, $data);
    }
    fclose($fp);
}
?>

Could someone help me to figure out this.

1
  • Have you enabled error reporting? You've forgotten the $ symbol all around. Commented Jan 1, 2022 at 10:47

1 Answer 1

3

Issues

  1. Passed long options arguments but trying to get short options https://www.php.net/manual/en/function.getopt.php
  2. Use = instead of : in the command
  3. Invalid variable syntax. missing $
  4. Incomplete logic

Command

php myscript.php --file=file1.csv --unique-combinations=file2.csv

Working Code

<?php
$files = getopt("", ["file:", "unique-combinations:"]);

if (!isset($files["file"])) {
    echo "Please provide a CSV file with parameter file";
} else if (!isset($files["unique-combinations"])) {
    echo "Please provide a file name to save unique combinations with parameter unique-combinations";
} else {
    $datas = array_count_values(file($files["file"]));;
    $fp = fopen($files["unique-combinations"], 'w');

    foreach ($datas as $data => $value) {
        fputcsv($fp, explode(',', trim($data)));
    }
    fclose($fp);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.