php continue "foreach" after return - php

I am working on a WordPress plugin for a specific theme but have a general question,
I have an array and want to do something with each object and return the result.
everything is Ok but the "foreach" only works for the first object of array and I think its because of "return" but for some reasons I cannot use "echo" instead of return.
this is my code:
$cast_list = array(
"composite_cast",
"graphic_designer_cast",
"product_manager_cast",
"render_cast",
"the3d_cast",
"story_board_cast"
);
foreach ($cast_list as $value)
{
$user_field = get_field($value);
}
return $user_field;
}
I have read other similar topics but passing the variable to another function to do the "return" job for me also not works

Your doubt: the "foreach" only works for the first object of array and I think its because of "return"
No this not for return it's because of variable overwriting inside the foreach() loop every time. Actually you're not returning only the first element, here you're returning the last element because you're overwriting $user_field variable every time within foreach() loop
Try instead to push result to it using $user_field[] and then you're good to go
$cast_list = array(
"composite_cast",
"graphic_designer_cast",
"product_manager_cast",
"render_cast",
"the3d_cast",
"story_board_cast"
);
foreach ($cast_list as $value)
{
$user_field[] = get_field($value);
}
return $user_field;

All the functions work until the return keyword. You need to create a new array and append all the edited elements to it and then return it.
$user_fields = array();
foreach ($cast_list as $value)
{
array_push($user_fields, get_field($value));
}
return $user_fields;
Or you even can work on each field right in the loop and return nothing.

Related

Multidimensional array into POST call using foreach loop PHP

Looking for some advise with regards to multidimensional Arrays, pushing the vars into a POST call within a foreach loop.
I currently have a foreach loop containing an IF clause:
foreach ($responseData['data'] as $key => $value) {
if (strtotime($value['attributes']['created_time']) > $currentDateMinusThirtyMinutes) {
array_push($emails, $value['attributes']['email']);
}
}
This is supposed to fetch the Email for all arrays which meet the condition of being created in the last 30 minutes.
However, now i am stuck, I need to fetch multiple other variables and call on a POST call similar to the below:
https://developer.example.co.za/{$PAGE}/create?reference={$ID}&currency=ZAR&amount={$AMOUNT}&firstname={$FIRST}&lastname={$LAST}&email={$EMAIL}&sendmail=true
What i need to know is, is there a better way to treat the foreach loop?
Is foreach the right way to go?
In essence I would need to run through each of the $responseData['data'] returns and make a POST call to the above URL.
Any advise would be appreciated.
Fixed this by creating a Data_array which stored the values I required, then adding the POST call inside the foreach loop which then did the trick.
The foreach ended up looking like this:
foreach ($responseData['data'] as $key => $value) {
if (strtotime($value['attributes']['created_time']) > $currentDateMinusThirtyMinutes) {
$data_array[] = array(
"id" => $value['attributes']['id'],
***add rest of vars you want***
);
***Add POST call or whatever else you want to do***
}
}
Thanks #darklightcode for pointing me to the idea of splitting out just the variables I wanted.

Select only arrays for foreach

I've got a foreach statement that on an item that has both objects and arrays in it.
foreach($result as $data)
that contains both arrays and objects. how do i specify the foreach to only select to loop through one or the other? when it loops through them all it takes forever
I had tried foreach($result->data as $data) but then it errors on the arrays telling me it is trying to get property of an object, which is understandable. once I add an if statement to check if the first result is an object it almost triples the script run time since there are so many results.
Well you could just use is_object() and is_array() (both return a boolean):
if (is_object($var)) {
// do something
} else if (is_array($var)) {
// well then, do something else
}

Object pushed to array overites

I've got strange thing, it's probably simple but I can't find a solution for it. Here is part of the code:
$counter = 0;
$autoload_view_instace = new Logic_InvoiceCostData;
$sub_view_cost = array();
foreach($invoceCostData as $data)
{
$counter++;
$parm = $autoload_view_instace->edit_view_data($autoload_view, $data, $counter);
array_push( $sub_view_cost, $parm);
}
The loop calls the edit_view_data method which returns an object with some values. That object should be placed at the end of the array in each iteration without changing values of objects previously added. But after each iteration, all objects in the array have the same value as the newly added object.
apparently the array_push syntax is correct.. and it should work .. however you can do the same thing using.
$sub_view_cost[]=$parm ;
and make sure each time $parm get the correct value

Strange foreach loop after modifying array

As I wrote some code, PHP confused me a little as I didn't expected the result of the following code:
$data = array(array('test' => 'one'), array('test' => 'two'));
foreach($data as &$entry) {
$entry['test'] .= '+';
}
foreach($data as $entry) {
echo $entry['test']."\n";
}
I think it should output
one+
two+
However the result is: http://ideone.com/e5tCsi
one+
one+
Can anyone explain to me why?
This is expected behaviour, see also https://bugs.php.net/bug.php?id=29992.
The reference is maintained when using the second foreach, so when using the second foreach the value of $entry, which points still to $data[1], is overwritten with the first value.
P.s. (thanks to #billyonecan for saying it): you need to unset($entry) first, so that your reference is destroyed.
This is mentioned specifically in the documentation for foreach. You should unset the loop variable when it gets elements of the array by reference.
Warning
Reference of a $value and the last array element remain even after the
foreach loop. It is recommended to destroy it by unset().

Foreach() value is set, after value disappears

I am trying to add a new key to an existing numerical indexed array using a foreach() loop.
I wrote this piece of code:
foreach($new['WidgetInstanceSetting'] as $row){
$row['random_key'] = $this->__str_rand(32, 'alphanum');
debug($row);
}
debug($new);
The first debug() works as I expected: the 'random_key' is created in the $new array.
Now, the problem is that the second debug() shows the $new array, but without the newly added key.
Why is this happening? How can I solve this problem?
$row ends up being a copy in the scope of the foreach block, so you really are modifying a copy of it and not what's in the original array at all.
Stick a & in your foreach to modify the $row array within your $new array by reference:
foreach($new['WidgetInstanceSetting'] as &$row){
And as user576875 says, delete the reference to $row in case you use that variable again to avoid unwanted behavior, because PHP leaves it around:
foreach($new['WidgetInstanceSetting'] as &$row){
$row['random_key'] = $this->__str_rand(32, 'alphanum');
debug($row);
}
unset($row);
debug($new);
Use the & to get a by reference value that you can change.
foreach($new['WidgetInstanceSetting'] as &$row){
$row['random_key'] = $this->__str_rand(32, 'alphanum');
debug($row);
}
debug($new);
You need to access the element by reference if you want to modify if within the array, as follows:
foreach($new['WidgetInstanceSetting'] as &$row) {
$row['random_key'] = $this->__str_rand(32, 'alphanum');
}
you are not creating random_key in $new array you are creating it in $row

Categories