Trying to do:

for($i = 0; $i <= $argc; $i++) { $sum += $argc[$i]; } echo $sum; 

But it's not right. It is necessary that the console executes this file with a parameter (numbers entered by the user), for example php file.php 235

  • not clear .... input 235 and the output should be 10? Но это не правильно - what exactly is meant by this? - Alexey Shimansky
  • for($i = 0; $i < strlen($argv[1]); $i++) { $sum += (int)$argv[1][$i]; } for($i = 0; $i < strlen($argv[1]); $i++) { $sum += (int)$argv[1][$i]; } ? - Alexey Shimanskyy
  • Alexey, it worked. Thank. Just please explain to me why $ argv [1] - Beginner
  • why not $ argv [o]. In array, with index 0 begins. - Beginner

2 answers 2

If the numbers are written in one word (number), then they need to be divided:

 if (isset($argv[1])) { $numbers = trim($argv[1]); $numbers_list = str_split($numbers); $sum = 0; foreach ($numbers_list as $num) { $num = intval($num); $sum += $num; } echo $sum; } 
  • and why trim ($ argv [1]) and not trim ($ argv [0])? - Beginner
  • Because the string file.php (the name of the executable file) will be stored in $argv[0] . Just check: var_dump($argv); - doubleui
  • yes, thanks .. i got it. - Beginner

Try this simple solution.

 unset($argv[0]); echo array_sum(array_filter($argv, 'is_numeric')); 
  • The first argument $ argv [0] always contains the name of the file of the running script. - pank
  • @pank, thank you, I will add to the answer - ilyaplot