user982124
user982124

Reputation: 4622

Increment variable name in a loop

I'm struggling to get the correct syntax to to parse out the values from an array to use with the foreach loop. I have an array:

$contacts_array

which contains one or more names which I need to search on. The array looks like this:

Array
(
    [0] => PR1010

    [1] => PR1086
)   

If I was to manually generate the required PHP code with a known number of names it would look like this where there are 2 names to search on:

// Create first find request
$findreq1 =$fm->newFindRequest('Contacts');

// Create second find request
$findreq2 =$fm->newFindRequest('Contacts');


// Specify search criterion for first find request 
$findreq1->addFindCriterion('Name', $searchTerm);

// Specify search criterion for second find request 
$findreq2->addFindCriterion('Suburb', $searchTerm);;
        
// Add find requests to compound find command 
$request->add(1,$findreq1); 
$request->add(2,$findreq2); 

I need to generate the equivalent code for every name in the array. I know I need to use something like:

foreach($contacts_array as $contact_array => $value) 
{
} 

as well as:

$num = 1
$num++; } /* foreach record */

I'm just not sure how to bring this all together so that it increments the $findreq1 variables as I go. All my attempts so far generate errors. If anyone can show me how to combine this together that would be greatly appreciated.

Upvotes: 0

Views: 727

Answers (2)

neutron
neutron

Reputation: 81

You guys beat me to it.

    <?php
    $contacts = Array('PR1010','PR1086');
    //print_r($contacts);

    foreach ($contacts as $key => $value) {
    //echo "key: ".$key." - Value: ".$value."<br>";

    $findreq1 = $fm->newFindRequest('Contacts');
    $findreq1->addFindCriterion('Name', $value); // this is where the Array's value is passed too, it is looped for every value in the Array
    $request->add(1,$findreq1); 

    // do more here 
    }
    ?>

Upvotes: 1

Mihai Matei
Mihai Matei

Reputation: 24276

<?php 
    for($i = 0; $i < count($contacts_array); $i++) { 
        ${'findreq' . ($i+1)} = $fm->newFindRequest('Contacts');
        ${'findreq' . ($i+1)}->addFindCriterion('Name', $contacts_array[$i]);
        $request->add($i+1, ${'findreq' . ($i+1)});
    }
?> 

Read more about Dynamic variable names in PHP

Upvotes: 1

Related Questions