skip to Main Content

I have a situation where one array is needed to be (appended or pushed) into multiple arrays I am testing against. My project is WordPress based, but this is a general PHP question. If I have the following setup:


    $tq_exact_matches = array('relation' => 'AND');
    $tq_any_matches = array('relation' => 'OR');

    //I WANT MY ARRAY BELOW TO ALSO BE STORED IN $tq_any_matches[], NOT JUST $tq_exact_matches[]
    //HOW CAN I DO THAT WITHOUT WRITING IT TWICE?

        $tq_exact_matches[] = array(
            'taxonomy' => 'focus-area',
            'field'    => 'name',
            'terms'    => $pluck_term_names_fa,
        );

2

Answers


  1. Use variable.

    $tq_exact_matches = array( 'relation' => 'AND' );
    $tq_any_matches   = array( 'relation' => 'OR' );
    
    // I WANT MY ARRAY BELOW TO ALSO BE STORED IN $tq_any_matches[], NOT JUST $tq_exact_matches[]
    // HOW CAN I DO THAT WITHOUT WRITING IT TWICE?
    
    $extra_tax_query = array(
        'taxonomy' => 'focus-area',
        'field'    => 'name',
        'terms'    => $pluck_term_names_fa,
    );
    
    $tq_exact_matches[] = $extra_tax_query;
    $tq_any_matches[]   = $extra_tax_query;
    
    Login or Signup to reply.
  2. You may do it like this

        $tq_exact_matches = array('relation' => 'AND');
    $tq_any_matches = array('relation' => 'OR');
    
    //I WANT MY ARRAY BELOW TO ALSO BE STORED IN $tq_any_matches[], NOT JUST $tq_exact_matches[]
    //HOW CAN I DO THAT WITHOUT WRITING IT TWICE?
    
        $m = array(
            'taxonomy' => 'focus-area',
            'field'    => 'name',
            'terms'    => 'we'
        );
        
        
        list($tq_exact_matches,$tq_any_matches) = [$tq_exact_matches + $m, $tq_any_matches + $m  ];
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search