2

How can I parse the result of var_dump in PHP? My PHP code calls a Python script as follows:

exec("python /home/content/51/5159651/html/perl/test_python.py $a0 $a1", $output);
var_dump($output);

where $a0 and $a1 are integers. test_python.py multiplies $a0 and $a1 correctly, but the result (for $a0=5 and $a1=7) of var_dump($output) is

array(1) { [0]=> string(2) "35" }

All I want is the answer, 35. Yes, I can parse the result using regex, but there must be a simpler way - e.g. something other than var_dump. The code for test_python.py is below, and I would be happy to modify it to get a simpler way to extract the result.

#!/usr/bin/python
import sys 
parameter1=int(sys.argv[1]);
parameter2=int(sys.argv[2]);

def main(parameter1, parameter2):
    output = parameter1*parameter2
    return output

output=main(parameter1, parameter2);
print(output);
1
  • var dump is almost certainly not the correct mechanism to use for this Commented Oct 2, 2015 at 1:43

1 Answer 1

4

You just need someone's phone number and you are doing a whole background check :)

var_dump($output);

Tells you everything about the response $output, but you just want the value. So

echo $output[0];   //$output is an array and you need its first element.

So your var_dump needs to go.

exec("python /home/content/51/5159651/html/perl/test_python.py $a0 $a1",  $output);
echo $output[0];   // will say 35 for 5 and 7

A little extra

This is the explanation of var_dump output

array(1) { [0]=> string(2) "35" }

That means $output is an array with 1 element which is on index 0. Element type = string and its length = 2 and its value = 35

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

1 Comment

Thanks for your answer!

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.