foreach without doing a loop in PHP - php

How is it possible to perform a foreach function without doing a loop for example
foreach($result['orders'] as $order) {
But I don't want to do a foreach I want something like
$result['orders'] == $order;
Or something like that instead of doing it inside an loop because $result['orders'] is only returning 1 result anyway so I don't see the point in doing it in a loop.
Thank you

You can get the first (and apparently only) element in the array with any array function that gets an element from the array, e.g. array_pop() or array_shift():
$order = array_shift( $result['orders']);
Or list():
list( $order) = $result['orders'];
Or, if you know it's numerically indexed, access it directly:
$order = $results['orders'][0];

Are you maybe just looking for this?
$result['orders'] = $result['orders'][0];

You have a comparison operator (==) rather than an assignment operator (=) in your second code example. If you are just trying to set a variable equal to a position in an array, you can use:
$order = $results['orders'];
I am not sure if that is what you are trying to accomplish though.

Related

PHP: Can't use function return value in write context

Can't use function return value in write context.
All the search result responses say its something to do with the empty function, but I'm not using that?
foreach ($permission as explode(',', $permissionString)) { // line 44
if ($this->hasPermission($permission))
$count++;
}
In a foreach the expression on the left of the as should be the array that you want to iterate through, and the expression on the right is a variable that gets overwritten with the value of each element inside the array.
The reason that you get an error is because php is trying to write an element of $permission into explode(',', $permissionString), but this returns an error because explode(',', $permissionString) is a function call, not a variable, and only variables can be written to.
To fix this, try reversing the order of the as, like this:
foreach (explode(',', $permissionString) as $permission) {

return empty array in php

I have a function that returns an array, and is passed to foreach i.e.
foreach(function() as $val)
Since the array I am returning is declared in a series of if statements, I need to return an empty array if all the if statements are evaluated to false. Is this a correct way to do it?
if (isset($arr))
return $arr;
else
return array();
I would recommend declaring $arr = array(); at the very top of the function so you don't have to worry about it.
If you are doing the check immediately before you return, I do not recommend isset. The way you are using foreach is depending on an array being returned. If $arr is set to a number, for example, then it will still validate. You should also check is_array(). For example:
if (isset($arr) && is_array($arr))
return $arr;
else
return array();
Or in one line instead:
return (isset($arr) && is_array($arr)) ? $arr : array();
But, like I said, I recommending declaring the array at the very top instead. It's easier and you won't have to worry about it.
To avoid complexity, Simply
return [];

Array in a recursive function

I have this recursive function in which I must use an array for memory and verification of used data, meaning, after a string has been used i would like to remember that it has been used so i will not go over that string again in the next iteration.
The problem is after the first iteration the array is considered NULL.
So my question is this : How do i pass an array in a recursive function ? or how do i work with arrays in recursive function?
I looked this up here and though there are many similar questions none answer my one.
Note: I understand that anything that can be done with recursion can be done with a loop... yet... this is the function. And like i mentioned on the 2nd iteration the array is considered to be NULL and i get this warning:
array_push() expects parameter 1 to be array, null given in...
Here is the logic of the function:
// Set Vars...
$Str = 'someData';
$S_Array = array();
// initial call...
GetData($Str, $S_Array);
function GetData ($string, $array)
{
// string manipulations code...
.
.
.
.
// Attempt to Store in array
array_push($array, $string);
foreach ($array as $val) {
// Recursive Call...
GetData($val, $array);
}
}
You are using array_push wrong -- the order of the arguments is switched. And there's really no need to use array_push at all, since the same result can be achieved with
$array[] = $string;

how to delete item from an array with filter?

I want to filter and delete an item from an array. is it possible to do it with array_filter() ?
//I want to delete these items from the $arr_codes
$id = 1223;
$pin = 35;
//Before
$arr_codes = Array('1598_9','1223_35','1245_3','1227_11', '1223_56');
//After
$arr_codes = Array('1598_9','1245_3','1227_11', '1223_56');
Thanks!
You can find the index of the value you are interested in with array_search and then unset it.
$i = array_search('1223_35',$arr_codes);
if($i !== false) unset($arr_codes[$i]);
array_filter does not take userdata (parameters). array_walk() does. However, none of the iterator function allow modifying the array structure within the callback.
As such, array_filter() is the appropriate function to use. However, since your comparison data is dynamic (per your comment), you're going to need another way to obtain comparison data. This could be a function, global variable, or build a quick class and set a property.
Here is an example using a function.
array_filter($arr, "my_callback");
function my_callback($val) {
return !in_array($val, get_dynamic_codes());
}
function get_dynamic_codes() {
// returns an array of bad codes, i.e. array('1223_35', '1234_56', ...)
}

cleanest way to skip a foreach if array is empty [duplicate]

This question already has answers here:
Invalid argument supplied for foreach()
(20 answers)
Closed 7 years ago.
Not a major problem but I was wondering if there is a cleaner way to do this. It would be good to avoid nesting my code with an unnecessary if statement. If $items is empty php throws an error.
$items = array('a','b','c');
if(!empty($items)) { // <-Remove this if statement
foreach($items as $item) {
print $item;
}
}
I could probably just use the '#' error suppressor, but that would be a bit hacky.
There are a million ways to do this.
The first one would be to go ahead and run the array through foreach anyway, assuming you do have an array.
In other cases this is what you might need:
foreach ((array) $items as $item) {
print $item;
}
Note: to all the people complaining about typecast, please note that the OP asked cleanest way to skip a foreach if array is empty (emphasis is mine). A value of true, false, numbers or strings is not considered empty.
In addition, this would work with objects implementing \Traversable, whereas is_array wouldn't work.
The best way is to initialize every bloody variable before use.
It will not only solve this silly "problem" but also save you a ton of real headaches.
So, introducing $items as $items = array(); is what you really wanted.
$items = array('a','b','c');
if(is_array($items)) {
foreach($items as $item) {
print $item;
}
}
If variable you need could be boolean false - eg. when no records are returned from database or array - when records are returned, you can do following:
foreach (($result ? $result : array()) as $item)
echo $item;
Approach with cast((Array)$result) produces an array of count 1 when variable is boolean false which isn't what you probably want.
I wouldn't recommend suppressing the warning output. I would, however, recommend using is_array instead of !empty. If $items happens to be a nonzero scalar, then the foreach will still error out if you use !empty.
I think the best approach here is to plan your code so that $items is always an array. The easiest solution is to initialize it at the top of your code with $items=array(). This way it will represent empty array even if you don't assign any value to it.
All other solutions are quite dirty hacks to me.
foreach((array)$items as $item) {}
i've got the following function in my "standard library"
/// Convert argument to an array.
function a($a = null) {
if(is_null($a))
return array();
if(is_array($a))
return $a;
if(is_object($a))
return (array) $a;
return $_ = func_get_args();
}
Basically, this does nothing with arrays/objects and convert other types to arrays. This is extremely handy to use with foreach statements and array functions
foreach(a($whatever) as $item)....
$foo = array_map(a($array_or_string)....
etc
Ternary logic gets it down to one line with no errors. This solves the issue of improperly cast variables and undefined variables.
foreach (is_array($Items) || is_object($Items) ? $Items : array() as $Item) {
It is a bit of a pain to write, but is the safest way to handle it.
You can check whether $items is actually an array and whether it contains any items:
if(is_array($items) && count($items) > 0)
{
foreach($items as $item) { }
}
Best practice is to define variable as an array at the very top of your code.
foreach((array)$myArr as $oneItem) { .. }
will also work but you will duplicate this (array) conversion everytime you need to loop through the array.
since it's important not to duplicate even a word of your code, you do better to define it as an empty array at top.

Categories