array_intersect with unknown number of arrays

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Markus Ernst

    array_intersect with unknown number of arrays

    Hi

    I have a question regarding array_intersect () in PHP 4.3. There are several
    arrays created on the fly, such as:

    $values['apples'];
    $values['bananas'];
    $values['pears'];

    To extract only the values they have in common I tried this:

    $command = "array_intersec t(";
    for ($i=0; $i<count($value s); $i++) {
    $command .= "\$values['$values[$i]'],";
    }
    $command = substr($command , 0, -1);
    $command .= ");";
    $result = eval($command);

    This does not seem to work and also is quite complicated. Does somebody know
    a better solution?

    Thanks
    Markus


  • Steve

    #2
    Re: array_intersect with unknown number of arrays

    [color=blue]
    > I have a question regarding array_intersect () in PHP 4.3. There are several
    > arrays created on the fly, such as:
    >
    > $values['apples'];
    > $values['bananas'];
    > $values['pears'];
    >
    > To extract only the values they have in common I tried this:
    >
    > $command = "array_intersec t(";
    > for ($i=0; $i<count($value s); $i++) {
    > $command .= "\$values['$values[$i]'],";
    > }
    > $command = substr($command , 0, -1);
    > $command .= ");";
    > $result = eval($command);
    >
    > This does not seem to work and also is quite complicated. Does somebody know
    > a better solution?[/color]

    The user comments in the docs for array_intersect suggest using
    call_user_func_ array() to pass an arbitrary number of arguments.
    Looks like you should be able to use:

    $result = call_user_func_ array( 'array_intersec t', $values );

    (untested, got to catch a bus!)

    ---
    Steve

    Comment

    • Markus Ernst

      #3
      Re: array_intersect with unknown number of arrays

      Steve wrote:
      [...][color=blue]
      > The user comments in the docs for array_intersect suggest using
      > call_user_func_ array() to pass an arbitrary number of arguments.
      > Looks like you should be able to use:
      >
      > $result = call_user_func_ array( 'array_intersec t', $values );[/color]

      Works perfectly! I had even read this note, but as I did not understand the
      examples provided I did not realize that it was what I looked for. Seems
      like it's worth to have a closer look at PHP's function functions.

      Thanks a lot for your input!

      --
      Markus


      Comment

      Working...