How do I pass an array as an argument in PHP and receive all the data in the shell?

Asked

Viewed 79 times

2

Example:

 <?php
            $param=array(valor, valor2, valor3);
            $return = shell_exec("sh teste.sh $param");
            echo "<pre>$return</pre>";
  ?>

Shell script:

#!/bin/bash
param=$1
echo $param

That way only the word returns to me array, I tried to receive as array but it did not work.

1 answer

1


Just pass the array elements separated by space:

$return = shell_exec("sh teste.sh ". implode(' ', $param));

And in the shell script these values will be in the special variable $@, which can be covered with a for:

for arg in $@
do
    echo $arg
done

This prints each element on a line. But if you want everything on the same line:

echo "$@"

If you want to store the contents of $@ in a variable, it gets a little more "boring":

param=("$@")

# tudo na mesma linha
echo "${param[*]}"

# ou um por linha
for arg in ${param[@]}
do
    echo $arg
done
  • gave just right!!!

  • the guard section the content did not work, has another form of guard in a variable?

  • @Robertsousa To keep everything in one variable I only know this way

  • solve like this: COUNT=$(echo $@ | awk '{print $1;}') separating the values and counting in for

  • but besides the array, I wanted to pass two more variables and the array, but it messes up when I get in shell_script, $1 and $2 $@that way, but in $1 and $2 comes the array too!!

  • @Robertsousa The shell script takes all the arguments at once and it has no way of knowing what was an array before and what wasn’t (pro script is all a large list of parameters), since PHP knew that. If you want to separate specific arguments into their own variables, you have to do it manually - search about shift, maybe that’s what you need

  • I also suggest to search here on the site, and if there is not something like that, there is the case of ask another question :-)

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.