AND in a PHP foreach loop? - php

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.)

Related

How Can I Select Data by Name From Array in PHP?

I have an array like this:
Array(
[0]=>Array([uploaderName]=>x[uploadedImageName]=>k6gIjfO[uploaderIp]=>195.155.116.217[uploader]=>e0699587cbfd[uploadedServer]=>alpha)
[1]=>Array([uploaderName]=>x[uploadedImageName]=>byUTyJo[uploaderIp]=>195.155.116.217[uploader]=>e0699587cbfd[uploadedServer]=>alpha)
[2]=>Array([uploaderName]=>x[uploadedImageName]=>oSVEnNk[uploaderIp]=>195.155.116.217[uploader]=>e0699587cbfd[uploadedServer]=>alpha)
[3]=>Array([uploaderName]=>x[uploadedImageName]=>Dj7GRYS[uploaderIp]=>195.155.116.217[uploader]=>e0699587cbfd[uploadedServer]=>alpha)
[4]=>Array([uploaderName]=>x[uploadedImageName]=>upsb8IC[uploaderIp]=>195.155.116.217[uploader]=>e0699587cbfd[uploadedServer]=>alpha)
[5]=>Array([uploaderName]=>x[uploadedImageName]=>YoEEzGi[uploaderIp]=>195.155.116.217[uploader]=>e0699587cbfd[uploadedServer]=>alpha)
[6]=>Array([uploaderName]=>x[uploadedImageName]=>st3dLNs[uploaderIp]=>195.155.116.217[uploader]=>e0699587cbfd[uploadedServer]=>alpha)
[7]=>Array([uploaderName]=>x[uploadedImageName]=>LBNpiIG[uploaderIp]=>195.155.116.217[uploader]=>e0699587cbfd[uploadedServer]=>alpha)
[8]=>Array([uploaderName]=>x[uploadedImageName]=>mFYDmBG[uploaderIp]=>195.155.116.217[uploader]=>e0699587cbfd[uploadedServer]=>alpha)
[9]=>Array([uploaderName]=>x[uploadedImageName]=>z03kSx1[uploaderIp]=>195.155.116.217[uploader]=>e0699587cbfd[uploadedServer]=>alpha)
)
I want to get any image's data from this array.
Example: When user shows uploadedImageName == jCPjeWv, I wan't to get who is it's uploader.
Simple, just use foreach
$arr = array(/* content here */);
foreach($arr as $value){
if($value['uploadedImageName'] == 'jCPjeWv'){
echo $value['uploaderName'];
break;
}
}
Just for fun, here's another way:
echo array_column($array, 'uploaderName', 'uploadedImageName')['jCPjeWv'];
Get an array of uploaderName with the index set to uploadedImageName
Access the index using the uploadedImageName 'jCPjeWv'
Obviously to do it multiple times you would want to actually create a new array:
$images = array_column($array, 'uploaderName', 'uploadedImageName');
echo $images['jCPjeWv'];
If you want to access the other values as well, then use null instead of uploaderName:
$images = array_column($array, null, 'uploadedImageName');
echo $images['jCPjeWv']['uploaderName'];
echo $images['jCPjeWv']['uploaderIp'];
NOTE: These ways only work if the uploadedImageName is unique.
A foreach is possible, but I think it's important to learn the array functions as well so I'm just going to put this example here.
$uploadedImageName = 'jCPjeWv';
$filtered = array_filter($array, function($value) use ($uploadedImageName) {
return ($value['uploadedImageName'] == $uploadedImageName);
});
This will return a $filtered with the other arrays removed since their $value['uploadedImageName'] will not equal $uploadedImageName.
For more info check out the http://php.net/manual/en/function.array-filter.php manual.

array_push not working within function, PHP

I have this case when I have array_push inside function and then I need to run it inside foreach filling the new array. Unfortunately I can't see why this does not work. Here is the code:
<?php
$mylist = array('house', 'apple', 'key', 'car');
$mailarray = array();
foreach ($mylist as $key) {
online($key, $mailarray);
}
function online($thekey, $mailarray) {
array_push($mailarray,$thekey);
}
print_r($mailarray);
?>
This is a sample function, it has more functionality and that´s why I need to maintain the idea.
Thank you.
PHP treats arrays as a sort of “value type” by default (copy on write). You can pass it by reference:
function online($thekey, &$mailarray) {
$mailarray[] = $thekey;
}
See also the signature of array_push.
You need to pass the array by reference.
function online($thekey, &$mailarray) {

foreach array function storing in a variable?

$numbers = array('1','2');
$numberlist = foreach($numbers as $number) {
echo $number;
}
As you can see what I'm trying to do it doesn't work is there any other way to store a foreach function as a variable?
$numberList = function( $input )
{
foreach( $input as $v )
echo $v;
};
$numberList( $numbers );
See PHP Anon
Note: Anonymous functions are available since PHP 5.3.0.
(The function should be $numberList with a capital L in order for it to work properly.)
If you're trying to store a code reference to the foreach loop in the $numberlist variable, that can't be done: loops are not functions.
If you want an object you can cycle on, you need to build an interator. If this is the case, I suggest you take a look at Standard PHP Library.
I think what Matthew is trying to do is store a function in a variable in PHP. I think this link is what you're looking for:
http://php.net/manual/en/functions.variable-functions.php

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);

Make 1d Array from 1st member of each value in 2d Array | PHP

How can you do this? My code seen here doesn't work
for($i=0;i<count($cond);$i++){
$cond[$i] = $cond[$i][0];
}
It can be as simple as this:
$array = array_map('reset', $array);
There could be problems if the source array isn't numerically index. Try this instead:
$destinationArray = array();
for ($sourceArray as $key=>$value) {
$destinationArray[] = $value[0]; //you may want to use a different index than '0'
}
// Make sure you have your first array initialised here!
$array2 = array();
foreach ($array AS $item)
{
$array2[] = $item[0];
}
Assuming you want to have the same variable name afterwards, you can re-assign the new array back to the old one.
$array = $array2;
unset($array2); // Not needed, but helps with keeping memory down
Also, you might be able to, dependant on what is in the array, do something like.
$array = array_merge(array_values($array));
As previously stated, your code will not work properly in various situation.
Try to initialize your array with this values:
$cond = array(5=>array('4','3'),9=>array('3','4'));
A solution, to me better readable also is the following code:
//explain what to do to every single line of the 2d array
function reduceRowToFirstItem($x) { return $x[0]; }
// apply the trasnformation to the array
$a=array_map('reduceRowTofirstItem',$cond);
You can read the reference for array map for a thorough explanation.
You can opt also for a slight variation using array_walk (it operate on the array "in place"). Note that the function doesn't return a value and that his parameter is passed by reference.
function reduceToFirstItem(&$x) { $x=$x[0]; }
array_walk($cond, 'reduceToFirstItem');
That should work. Why does it not work? what error message do you get?
This is the code I would use:
$inArr;//This is the 2D array
$outArr = array();
for($i=0;$i<count($inArr);$i++){
$outArr[$i] = $inArr[$i][0];
}

Categories