Provoque element change in a foreach in Laravel - php

I have 2 loops,
I would like that for each iteration of fighters2, $fighter1 also advance 1 element. Is is posible to do it with foreach????
foreach ($fighters1 as $fighter) {
foreach ($fighters2 as $fighter2) {
}
}

not sure if i understand the question correctly, but here is the answer to how i understood the question.
if your arrays are the same size you could do sth like this:
foreach($fighters1 as $index => $fighter) {
$fighter2 = $fighters2[$index];
//do what you need to do with $fighter and $fighter2
}
that is assuming both arrays are same size and have numeric indexes

Maybe using next() might help you.
foreach ($fighters1 as $fighter) {
$nextFighter1 = next($fighters1);
foreach ($fighters2 as $fighter2) {
//do whatever you need
}
}
next() reference
Bye!

Related

PHP Repeat n times inside a function

I am trying to use item[1],item[2]... item[n] inside php functions like array_diff, max etc.
I use foreach loop like this to get the items
$n=1;
foreach ($arrays as $array) {
$item[$n] = $array;
$n++;
}
# how can I define item[1] through item[n] like:
print_r(max(item[1],item[2]...item[n]));
print_r(array_diff(item[1],item[2]...item[n]));
I searched but could not find a solution, please point me to the url if this has already been answered. Thanks.
Even though I don't see a problem, you can do this:
Hope it helps
foreach ($arrays as $k=>$array) {
$item[$k] = $array;
}
print_r(max($item));
print_r(array_diff($arrays,$item));

Error merging arrays in PHP

I have nested arrays and want to append the content of one array into another when the keys match. Here is my function but instead of appending it is replacing.
function MergeArrays($arr, $ins)
{
if(is_array($arr))
{
if(is_array($ins))
foreach($ins as $k=>$v)
{
if(isset($arr[$k])&&is_array($v)&&is_array($arr[$k]))
{
$arr[$k] = MergeArrays($arr[$k], $v);
}
else
{
// This is the new loop :)
// while (isset($arr[$k]))
// $k++;
// HERE IS WHERE I WANT TO APPEND INSTEAD OF ADD
$arr[$k] = $v;
}
}
}
else if(!is_array($arr)&&(strlen($arr)==0||$arr==0))
{
$arr=$ins;
}
return($arr);
}
Any recommendations?
Thanks
You can merge the entries by either adding the arrays together, or using array_merge to merge the arrays into a new one.
Any reason you're not using array_merge_recursive to solve this without custom code?
I'm not sure I'm reading the question properly, I'm a little confused as to what you're doing, but this might help:
As far as I can tell, you want to append to the value of $arr[k] with the value of $v. Therefore you want to concat these things together.
Therefore you want to use .= instead of = on the line below your comment.

AND in a PHP foreach loop?

Is it possible to have an AND in a foreach loop?
For Example,
foreach ($bookmarks_latest as $bookmark AND $tags_latest as $tags)
You can always use a loop counter to access the same index in the second array as you are accessing in the foreach loop (i hope that makes sense).
For example:-
$i = 0;
foreach($bookmarks_latest as $bookmark){
$result['bookmark'] = $bookmark;
$result['tag'] = $tags_latest[$i];
$i++;
}
That should achieve what you are trying to do, otherwise use the approach sugested by dark_charlie.
In PHP 5 >= 5.3 you can use MultipleIterator.
Short answer: no. You can always put the bookmarks and tags into one array and iterate over it.
Or you could also do this:
reset($bookmarks_latest);
reset($tags_latest);
while ((list(, $bookmark) = each($bookmarks_latest)) && (list(,$tag) = each($tags_latest)) {
// Your code here that uses $bookmark and $tag
}
EDIT:
The requested example for the one-array solution:
class BookmarkWithTag {
public var $bookmark;
public var $tag;
}
// Use the class, fill instances to the array $tagsAndBookmarks
foreach ($tagsAndBookmarks as $bookmarkWithTag) {
$tag = $bookmarkWithTag->tag;
$bookmark = $bookmarkWithTag->bookmark;
}
you can't do that.
but you can
<?php
foreach($keyval as $key => $val) {
// something with $key and $val
}
the above example works really well if you have a hash type array but if you have nested values in the array I recommend you:
or option 2
<?php
foreach ($keyval as $kv) {
list($val1, $val2, $valn) = $kv;
}
No, but there are many ways to do this, e.g:
reset($tags_latest);
foreach ($bookmarks_latest as $bookmark){
$tags = current($tags_latest); next($tags_latest);
// here you can use $bookmark and $tags
}
No. No, it is not.
You'll have to manually write out a loop that uses indexes or internal pointers to traverse both arrays at the same time.
Yes, for completeness:
foreach (array_combine($bookmarks_latest, $tags_latest) as $bookm=>$tag)
That would be the native way to get what you want. But it only works if both input arrays have the exact same length, obviously.
(Using a separate iteration key is the more common approach however.)

is there another samples of php foreach?

I looking for another samples of php foreach code that similar to the code as following:
foreach ($this->ask->post['books'] as $book) {
if ($book['qty']) {
$this->goto->add($book['book_id'], $book['qty'], (isset($book['opt'])) ? $book['opt'] : NULL);
}
}
I just want to save it as my collection, so, is there another samples of php foreach that You may know? let me know it. Thanks
Maybe this example can help you:
foreach($myArrayOfObject as $key=>$object) {
if($object->aPropertyOfMyObject) {
// do something...
}
}
You can also have a look to http://php.net/manual/en/control-structures.foreach.php
Do you specifically need foreach?
You can also use this:
<?php
$array = array(); // Imagine a filled array
array $max = count($array);
for($i=0;$i<$max;$i++) {
// Loop over the array
echo $array[$i]['name_of_key'];
}
?>

How do you remove an array element in a foreach loop?

I want to loop through an array with foreach to check if a value exists. If the value does exist, I want to delete the element which contains it.
I have the following code:
foreach($display_related_tags as $tag_name) {
if($tag_name == $found_tag['name']) {
// Delete element
}
}
I don't know how to delete the element once the value is found. How do I delete it?
I have to use foreach for this problem. There are probably alternatives to foreach, and you are welcome to share them.
If you also get the key, you can delete that item like this:
foreach ($display_related_tags as $key => $tag_name) {
if($tag_name == $found_tag['name']) {
unset($display_related_tags[$key]);
}
}
A better solution is to use the array_filter function:
$display_related_tags =
array_filter($display_related_tags, function($e) use($found_tag){
return $e != $found_tag['name'];
});
As the php documentation reads:
As foreach relies on the internal array pointer in PHP 5, changing it within the loop may lead to unexpected behavior.
In PHP 7, foreach does not use the internal array pointer.
foreach($display_related_tags as $key => $tag_name)
{
if($tag_name == $found_tag['name'])
unset($display_related_tags[$key];
}
Instead of doing foreach() loop on the array, it would be faster to use array_search() to find the proper key. On small arrays, I would go with foreach for better readibility, but for bigger arrays, or often executed code, this should be a bit more optimal:
$result=array_search($unwantedValue,$array,true);
if($result !== false) {
unset($array[$result]);
}
The strict comparsion operator !== is needed, because array_search() can return 0 as the index of the $unwantedValue.
Also, the above example will remove just the first value $unwantedValue, if the $unwantedValue can occur more then once in the $array, You should use array_keys(), to find all of them:
$result=array_keys($array,$unwantedValue,true)
foreach($result as $key) {
unset($array[$key]);
}
Check http://php.net/manual/en/function.array-search.php for more information.
if you have scenario in which you have to remove more then one values from the foreach array in this case you have to pass value by reference in for each:
I try to explain this scenario:
foreach ($manSkuQty as $man_sku => &$man_qty) {
foreach ($manufacturerSkus as $key1 => $val1) {
// some processing here and unset first loops entries
// here dont include again for next iterations
if(some condition)
unset($manSkuQty[$key1]);
}
}
}
in second loop you want to unset first loops entries dont come again in the iteration for performance purpose or else then unset from memory as well because in memory they present and will come in iterations.
There are already answers which are giving light on how to unset. Rather than repeating code in all your classes make function like below and use it in code whenever required. In business logic, sometimes you don't want to expose some properties. Please see below one liner call to remove
public static function removeKeysFromAssociativeArray($associativeArray, $keysToUnset)
{
if (empty($associativeArray) || empty($keysToUnset))
return array();
foreach ($associativeArray as $key => $arr) {
if (!is_array($arr)) {
continue;
}
foreach ($keysToUnset as $keyToUnset) {
if (array_key_exists($keyToUnset, $arr)) {
unset($arr[$keyToUnset]);
}
}
$associativeArray[$key] = $arr;
}
return $associativeArray;
}
Call like:
removeKeysFromAssociativeArray($arrValues, $keysToRemove);

Categories