Dev Anony Dev Anony - 1 year ago 122
PHP Question

How to output Simple Array Sum challenge of HackerRank in PHP?

I was just trying to get familiar with HackerRank environment and practice some problems.

I was attempting its 2nd challenge in Algorithms>Warmups:
Simple Array Sum

I have solved it and its working fine on my local machine.


function testSum($n,$x)
$x =explode(" ",$x);
echo $sum;
$handle = fopen ("php://stdin","r");
$arr_temp = fgets($handle);
$arr = explode(" ",$arr_temp);


But It keeps giving me same response every time:
Response on running code.

Please help me how to print results in hackerrank and what am I missing here. Thanks

Answer Source

I'm not the first one but let me try (mine works on too :)

/* simple solution for */

/* Read and parse input */
$handle = fopen ('php://stdin', 'r');
fscanf($handle, '%d', $n);
$numbers = explode(' ', fgets($handle));
array_walk($numbers, function (&$value) {
    $value = intval($value);

/* result: */
echo array_sum($numbers);

Simple step by step explanation

  1. Read user input - check the examples in the documentation.
  2. fscanf is really not needed here. In our case it reads number from input and stores the value in the $n variable. Check format description in the docs.
  3. fgets($handle) reads a string. Next we split the string into array using explode. These are all very basic and often used PHP functions, make sure to get familiar with them and read the documentation.
  4. We walk (array_walk) through the array and convert all elements to integers. We use anonymous function in the example. This is a bit more advanced technique and might be skipped here.
  5. Finally we calculate and output the sum using array_sum function.