PHP - using foreach with array
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 as I'm learning PHP as I go.
Thanks
Answers
<?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 php
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 } ?>