Reputation: 449
I have a Linux web server running a PHP/HTML page.
I need to save an output that has to interpreted as an array -
exec($instruction);
where the output will be
1 2 5 7 0 5 3 4
and I must be able to call out particular element in the array
echo $result[4]
so far the following attempts were unsuccessful
$result =exec($instruction);
or
$result = array(exec($instruction));
Update, So far I tried this -
$result = shell_exec($instruction);
$out = explode(" ",$result);
I got the expected output, but why doesn't exxplode() return individual elements?
Array ( [0] => 1 1 1 2 1 2 0 0 1 1 )
Upvotes: 3
Views: 21358
Reputation: 3870
I prefer to use:
$result = shell_exec($instruction);
$out = explode("\n",$result);
Because shell_exec function returns the complete output as string. If you have more than one line, you should use that.
Upvotes: 0
Reputation: 315
According to documentation (php.net) exec has a second parameter that is passed by reference called $output. So you can try:
exec($instruction, $results);
And then you can access $results that will be an array with each line as an element. So:
$results[0]
will have the first line of your output.
Upvotes: 14
Reputation: 449
Why explode did not work for me? The shell $instruction that I used returned "newline" or "\n". I had to split the string using "\n" as the delimiter. This worked for me -
$result = shell_exec($instruction);
$out = explode("\n",$result);
Upvotes: 4
Reputation:
$result =exec($instruction);
$result_array=explode(' ',$result);
or just
$result =explode(' ',exec($instruction));
Upvotes: 3