I'm looping through an array with foreach(), but for some reason, this particular line doesn't seem to like my array. It's strange, because I have another foreach that works with this array in a different file that works correctly. I've tried casting it to an array, but that just leaves me with empty strings returned to my other functions and a nested array.
Array structure:
Array (
[0] => http://example.com/example.html
[1] => http://developer.com/test.html
)
PHP
/*
* Sends forms post submissions to a second source
*
*/
public function send_to_third_party(){
//this is how we read options from the options database as seen in options.php
//get settings
$formIdsArray = explode(',', get_option('fts_form_id'));
$formUrlsArray = explode(',', get_option('fts_forward_url'));
print_r($formUrlsArray);
add_action("gform_post_submission", "post_again", 10, 2);
function post_to_url($url, $data) {
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded
",
'method' => 'POST',
'content' => http_build_query($data),
),
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
}
function post_again($entry, $form){
//if this form's ID matches the required id, forward it to corresponding URL
if(get_option('fts_forward_url')){ //check for empty forwarding URLs
if(is_array($formUrlsArray))
{
foreach($formUrlsArray as $key => $formUrl){
//post_to_url($formUrl, $entry);
}
}
else
{
echo "<pre>"; print_r($formUrlsArray); echo "</pre>";
}
}
}
}
Error
Warning: Invalid argument supplied for foreach() in *path* on line *line*
EDIT: The foreach is in an inner function inside a public function.
Try this, share with us the output.
if(is_array($formUrlsArray))
{
foreach($formUrlsArray as $key => $formUrl){
post_to_url($formUrl, $entry);
}
}
else
{
echo "<pre>"; print_r($formUrlsArray); echo "</pre>";
}
also consider typecasting $formUrlsArray:
$formUrlsArray = (array) $formsUrlArray;
Had the same issue where I was passing an array to a foreach in a function. Type casting the array before passing it to the foreach solved the issue.
So insert $formUrlsArray = (array) $formUrlsArray
as per below and it should work.
function post_again($entry, $form){
//if this form's ID matches the required id, forward it to
//corresponding URL
if(get_option('fts_forward_url')){ //check for empty forwarding URLs
$formUrlsArray = (array) $formUrlsArray
if(is_array($formUrlsArray))
{
foreach($formUrlsArray as $key => $formUrl){
//post_to_url($formUrl, $entry);
}
}
else
{
echo "<pre>"; print_r($formUrlsArray); echo "</pre>";
}
}
}