1

Trying to print an integer from an array in php.

I am attempting a question on the coding site hackerrank.

The pre-supplied function takes in a string input and manipulates it into an array like so:

<?php

$handle = fopen ("php://stdin","r");
fscanf($handle,"%d",$n);
$a = array();
for($a_i = 0; $a_i < $n; $a_i++) {
   $a_temp = fgets($handle);
   $a[] = explode(" ",$a_temp);
  array_walk($a[$a_i],'intval');
}

echo $a[0];

?>

However running

echo $a[0] 

results the following error:

PHP Notice:  Array to string conversion in solution.php on line 12

and outputs:

Array

I understand that this is because I am trying to manipulate the array as a string but I am not sure how else one could print out indexed values. Ideally I would like to use a c-type for loop:

for($x = 0; $x < $n; $x++) {
    echo $a[$x];
}

Using print_r($a[0]) gives the following output:

hackerrank output

4
  • You can use print_r() or var_dump() to see what's the value of an array Commented Feb 18, 2016 at 10:33
  • What would you expect/like the output to be? Commented Feb 18, 2016 at 10:58
  • the first integer in the array Commented Feb 18, 2016 at 11:03
  • So echo $a[0][0]...? Commented Feb 18, 2016 at 11:07

1 Answer 1

1

For printing an array use print_r().

Example: print_r($a[0]);

$a[0] is an array in this scope and not a string.

Sign up to request clarification or add additional context in comments.

3 Comments

Would it be possible for me to print just the integer at index 0? I've added an image of the output given by print_r($a[0])
You have a multidimensional array. To can use echo $a[0][0], which would print 11 in your case.echo $a[0][1] would print 2.
Yes that works-thanks. Might be out of scope, but what is the benefit of creating such an array?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.