I'm trying to work with array using array_walk() function such way:
<?php
$array = array('n1' => 'b1', 'n2' => 'b2', 'n3' => 'b3');
array_walk($array, function(&$val, $key) use (&$array){
echo $key."\n";
if ($key == 'n1')
$val = 'changed_b1';
if ($key == 'n2' || $key == 'n3') {
unset($array[$key]);
}
});
print_r($array);
Get:
n1
n2
Array
(
[n1] => changed_b1
[n3] => b3
)
It seems, what after deletion of 2nd element -- 3rd element don't be sended to callback function.
Use array_filter:
<?php
$filtered = array_filter($array, function($v,$k) {
return $k !== "n2" && $k !== "n3";
}, ARRAY_FILTER_USE_BOTH);
?>
See http://php.net/array_filter
What you can do is use a secondary array, which will give the effect that those nodes have been deleted, like;
<?php
$array = array('n1' => 'b1', 'n2' => 'b2', 'n3' => 'b3');
$arrFinal = array();
array_walk($array, function($val, $key) use (&$array, &$arrFinal){
echo $key."\n";
if ($key == 'n2' || $key == 'n3') {
//Don't do anything
} else {
$arrFinal[$key] = $val;
}
});
print_r($arrFinal);
https://eval.in/206159
From the documentation:
Only the values of the array may potentially be changed; its structure cannot be altered, i.e., the programmer cannot add, unset or reorder elements. If the callback does not respect this requirement, the behavior of this function is undefined, and unpredictable.
May be that's the reason why you don't get the desired output with your code. Hope it helps.
Possible alternatives:
If you still want to use array_walk(), simply create a new array and copy the 'required' elements i.e. with indices you don't want to delete into the new array. This is a preferred alternative if number of elements to be deleted are very large.
You could look into array_filter or array_map, both rely on applying a callback to every element of your array. You could simply put a condition there barring the indices you want to delete in this callback function. This would work if the number of elements you want to delete are very few.
If however, the elements to delete are contiguous and form a 'portion' of an array (in your case you wanted to remove n2 and n3 which are adjacent). You can use the function array_splice
Sidenote - I am refraining from putting in any code snippets as I have linked the relevant documentations and getting started with them should be a good exercise in itself.
I realize this is several years old, but I found the thread while looking for the solution to a similar situation.
I wound up using preg_grep to return only the array that I wanted to walk, in case anyone finds it useful.
So, in my case, I wanted to ignore files in a scandir array with a "." prefix (system files), then apply a new prefix to the remaining files.
Here's what I wound up with:
$fl = array_map(function($i){
return $new_prefix . "/" . $i;
}, preg_grep("/^[^\.]/", scandir($path)));
If you can build a regex to exclude the undesired array elements, this solution should work.
check the "array_walk" source code and u will see. array_walk use pos to fetch item, and in every loop, the pos move forward.
do {
/* Retrieve value */
zv = zend_hash_get_current_data_ex(target_hash, &pos);
/* Retrieve key */
zend_hash_get_current_key_zval_ex(target_hash, &args[1], &pos);
/* Move to next element already now -- this mirrors the approach used by foreach
* and ensures proper behavior with regard to modifications. */
zend_hash_move_forward_ex(target_hash, &pos);
/* Back up hash position, as it may change */
EG(ht_iterators)[ht_iter].pos = pos;
and reset pos to get value
/* Reload array and position -- both may have changed */
if (Z_TYPE_P(array) == IS_ARRAY) {
pos = zend_hash_iterator_pos_ex(ht_iter, array);
target_hash = Z_ARRVAL_P(array);
} else if (Z_TYPE_P(array) == IS_OBJECT) {
target_hash = Z_OBJPROP_P(array);
pos = zend_hash_iterator_pos(ht_iter, target_hash);
} else {
php_error_docref(NULL, E_WARNING, "Iterated value is no longer an array or object");
result = FAILURE;
break;
}
if key= n1; then next pos 1
if key= n2; then next pos 2
if key= n3; then next pos 3
when run [$key == 'n2'] , the next pos is 2 ; after unset , pos 2 is unreachable ,so the loop end.
so in actually ,then $key=='n3' will not happen, and u will get the result.
Related
I'm trying two combine two arrays based on the values names.
Here what I'm trying to do :
$array1 = ("fifa21","pes21","halflife2","carma2");
$array2 = ("fifa21_cover","pes21_cover","halflife2_cover");
I want to loop through both arrays and if value from array1 match value from array 2 it will list both values like this :
fifa21 - fifa21_cover
pes21 - pes21_cover
halflife2 - halflife2_cover
carma2 - default_cover
if not find anything in the array2, a default cover will be used.
Note: the arrays will be filled dynamically based in a scanDir (two different folders search) and the arrays can be sorted differently than shown in the example above.
This code will loop through array1 and check to see if the item cover exists in array2, if it does then it will echo out in the format you wanted.
$array1 = array("fifa21","pes21","halflife2","carma2");
$array2 = array("fifa21_cover","pes21_cover","halflife2_cover");
foreach ($array1 as $item) {
if (in_array($item."_cover", $array2)) {
echo "<p>".$item." - ".$item."_cover</p>\n";
} else {
// use default cover...
}
}
(because it is lunch time and I need to write some code)
Given two arrays:
$array1 = ["fifa21", "pes21", "halflife2", "carma2"];
$array2 = ["fifa21_cover", "pes21_cover", "halflife2_cover"];
A function such as this can walk through and look for items that start with those values:
function merge_arrays(array $array1, array $array2): array
{
$output = [];
array_walk(
$array1,
static function ($key) use ($array2, &$output) {
$items = array_filter($array2, static fn($f) => 0 === mb_strpos($f, $key));
if (count($items) === 1) {
$output[$key] = reset($items);
return;
}
if (count($items) === 0) {
$output[$key] = 'default_cover';
return;
}
throw new RuntimeException('More than one item found starting with key ' . $key);
}
);
return $output;
}
When called as:
print_r(merge_arrays($array1, $array2));
It will output:
(
[fifa21] => fifa21_cover
[pes21] => pes21_cover
[halflife2] => halflife2_cover
[carma2] => default_cover
)
For your use-case, it might be overly complicated when compared to a for loop, but it does the job.
Another version that more-blindly assumes only a one-to-one match could use the ?? operator for a null check, although I wouldn't recommend this. The more terse and compact that code looks, the more I find that it is usually very hard to reason about, especially in the future:
function merge_arrays(array $array1, array $array2): array
{
$output = [];
array_walk(
$array1,
static function ($key) use ($array2, &$output) {
$output[$key] = array_filter($array2, static fn($f) => 0 === mb_strpos($f, $key))[0] ?? 'default_cover';
}
);
return $output;
}
All code snipping provided works, however if the array values have extension it always assumes the default cover. I can figure it how using my code by removing the extension for compare purpose, and then I add it back.
Inside my loop I use this :
$keyvaluetemp = substr($keyvalue, 0, strrpos($keyvalue, "."));
the above it inside my first ForEach (where I check the first array), and then in the covers array I remove the "_cover" by nothing :
$keyvalue2temp = (str_replace("_cover", "",$keyvalue2));
then I use the following code inside the second ForEach to add the data to a DB:
// if fantart match the game file name so we associate it to the game and save to the DB
if ( stripos ( $keyvalue2temp , $keyvaluetemp ) !== FALSE )
{
$sql = "UPDATE listgames SET FanArt='$keyvalue2' WHERE Name='$keyvalue'";
$con->exec($sql);
}
// if fanart is empty we add a default picture
$checkifempty = "SELECT `FanArt` FROM `listgames` WHERE `Name` = '$keyvalue'";
$runsql = $con->query($checkifempty);
$row = $runsql->fetch(PDO::FETCH_ASSOC);
$fanartkey = $row['FanArt'];
if($fanartkey == '')
{
$sql = "UPDATE listgames SET FanArt='nopic.JPG' WHERE Name='$keyvalue'";
$con->exec($sql);
}
Later in my code I print the results from the DB. I don't know if this is the best approach, however it does exactly what I want :)
This question has been asked a thousand times, but each question I find talks about associative arrays where one can delete (unset) an item by using they key as an identifier. But how do you do this if you have a simple array, and no key-value pairs?
Input code
$bananas = array('big_banana', 'small_banana', 'ripe_banana', 'yellow_banana', 'green_banana', 'brown_banana', 'peeled_banana');
foreach ($bananas as $banana) {
// do stuff
// remove current item
}
In Perl I would work with for and indices instead, but I am not sure that's the (safest?) way to go - even though from what I hear PHP is less strict in these things.
Note that after foreach has run, I expected var_dump($bananas) to return an empty array (or null, but preferably an empty array).
1st method (delete by value comparison):
$bananas = array('big_banana', 'small_banana', 'ripe_banana', 'yellow_banana', 'green_banana', 'brown_banana', 'peeled_banana');
foreach ($bananas as $key=>$banana) {
if($banana=='big_banana')
unset($bananas[$key]);
}
2nd method (delete by key):
$bananas = array('big_banana', 'small_banana', 'ripe_banana', 'yellow_banana', 'green_banana', 'brown_banana', 'peeled_banana');
unset($bananas[0]); //removes the first value
unset($bananas[count($bananas)-1]); //removes the last value
//unset($bananas[n-1]); removes the nth value
Finally if you want to reset the keys after deletion process:
$bananas = array_map('array_values', $bananas);
If you want to empty the array completely:
unset($bananas);
$bananas= array();
it still has the indexes
foreach ($bananas as $key => $banana) {
// do stuff
unset($bananas[$key]);
}
for($i=0; $i<count($bananas); $i++)
{
//doStuff
unset($bananas[$i]);
}
This will delete every element after its use so you will eventually end up with an empty array.
If for some reason you need to reindex after deleting you can use array_values
How about a while loop with array_shift?
while (($item = array_shift($bananas)) !== null)
{
//
}
Your Note: Note that after foreach has run, I expected var_dump($bananas) to return an empty array (or null, but preferably
an empty array).
Simply use unset.
foreach ($bananas as $banana) {
// do stuff
// remove current item
unset($bananas[$key]);
}
print_r($bananas);
Result
Array
(
)
This question is old but I will post my idea using array_slice for new visitors.
while(!empty($bananas)) {
// ... do something with $bananas[0] like
echo $bananas[0].'<br>';
$bananas = array_slice($bananas, 1);
}
I'm currently working on a generic form creation class and had an issue yesterday.
I made a snippet to reproduce the problem.
Essentially I want to delete elements that are grouped from the original elements array after the whole group has been drawn and I'm doing this while looping over the elements array.
The code snippet should cover the problem, am I missing something here? From my knowledge deleting an element while foreach is completely safe and legal since foreach internally only uses a copy that may be modified during the loop.
$ids = array('a' => array(), 'b' => array(), 'c' => array());
$groups['g1'] = array('a', 'c');
foreach($ids as $id => $element) {
//var_dump($ids);
$g_id = '';
// search the id in all groups
foreach($groups as $group_id => $group) {
if(in_array($id, $group)) {
$g_id = $group_id;
break;
}
}
// element is part of a group
if($g_id !== '') {
//echo $g_id;
// element a and c gets unset within loop and should not be in $ids anymore
foreach($groups[$g_id] as $field_id) {
unset($ids[$field_id]);
echo $field_id;
}
unset($groups[$g_id]);
} else {
if($id === 'a' || $id === 'c')
echo $id;
}
}
Element 'c' gets unset within the foreach(groups ..) loop but is afterwards again outputted in the else branch. Also when i var_dump($fields) at the beginning i always get 'a', 'b' and 'c' inside. I'm using PHP 5.4.7.
Thanks in advance
EDIT: i made a mistake in the sample code, its now updated. All comments about using the wrong index (it would have been 0,1 etc) were correct of course.
The values when using var_dump are unset now, but i still get into the else with 'c' one time.
EDIT2:
Im not done with the original code but after reading through the comments I currently came up with following solution to the posted code snippet above:
$ids=array("a"=>array(),"b"=>array(),"c"=>array(),"d"=>array(),"e"=>array());
$groups=array(array("a"),array("c", "e"));
array_walk($groups,function($v,$i)use(&$ids){
$in_both = array_intersect(array_keys($ids),$v);
//var_dump($in_both);
foreach($in_both as $b) {
unset($ids[$b]);
}
});
print_r($ids);
or
$ids=array("a"=>array(),"b"=>array(),"c"=>array(),"d"=>array(),"e"=>array());
$groups=array(array("a"),array("c"));
array_walk($ids,function($v,$i)use(&$ids, $groups){
$in_both = array();
foreach($groups as $g) {
if(in_array($i,$g)) {
$in_both = array_intersect(array_keys($ids),$g);
}
}
foreach($in_both as $b) {
unset($ids[$b]);
}
});
print_r($ids);
Using a foreach does not work for me in this case, because i need to change the $ids array while the loop is iterating over it.
In the very most basic situation a code something like this:
$ids = array('a', 'b');
while(count($ids)) {
array_pop($ids);
echo 'pop';
}
echo 'empty';
Allthough foreach can change the original values from the array it will not change the copy of the array used for the iteration as nl-x already stated.
Thanks to Passerby for the idea of using array_walk for this.
EDIT3:
Updated code snipped once more. The second snipped allthough behaves undefined as well. Deleting elements from an array while iterating over its seems to be a bad idea.
Chris, if I understand correctly, you don't expect 'C' to be outputted in the else branch?
But it should be outputted. Your logic is:
you do foreach ids and start with id 'a'.
then you clear ids a and c from ids and delete the group g1 that contained 'a'. During this step the deleted ids will be outputted, being a and c. (Clearing a and c from ids will have no impact on the foreach($ids as $id) as foreach will continue with the untouched copy even after ids array has been cleared.)
then you do id 'b': it is not found in any group. (actually, there isn't any group left by now anyway)
so for 'b' you enter the else branch. But the if() inside the else branch prevents output
then you do id 'c', which is also not found in any group, because you have already deleted group g1! There are no groups left, remember?
so for 'c' you also enter the else branch. And this time the if() inside the else branch allows the output! The output being just c
So the total output is indeed acc.
It is good to know that a foreach() that continues with a untouched copy even after its elements were cleared, is a specific PHP thing. Other language do no necessarily do the same.
Spent some time reading your code, and I guess your procedure is:
For every element in $ids, check if it exists in some sub-array in $groups;
If it exists, delete everything in $ids that also exists in this sub-array.
Following the above logic, I come up with this:
$ids=array("a","b","c","d","e");
$groups=array(array("a","c"),array("c","e"));
array_walk($groups,function($v,$i)use(&$ids){
$ids=array_diff($ids,$v);
});
print_r($ids);//debug
Live demo
I'm double checking now. But I think unsetting an array with foreach is not really safe.
What I usually would do is take a foreach, and start with the highest indexes and descrease the index along the way. for($i = count($arr)-1; $i >= 0; $i--) { unset($array[$i]); }
I'll edit this post in a few minutes.
edit: i was confused. The for with $i++ is indeed the culprit. foreach is safe (in php! not in all languages)
<?php
$arr = Array(1,2,3,4,5,6,7,8,9,10);
foreach ($arr as $key=>$val)
unset($arr[$key]);
echo implode(',',$arr); // returns nothing
$arr = Array(1,2,3,4,5,6,7,8,9,10);
for ($i=0; $i<count($arr); $i++)
unset($arr[$i]);
echo implode(',',$arr); // returns 6,7,8,9,10
$arr = Array(1,2,3,4,5,6,7,8,9,10);
for ($i=count($arr)-1; $i>=0; $i--)
unset($arr[$i]);
echo implode(',',$arr); // returns nothing
?>
$ids[$field_id] does not exist, you are using the value instead of the key.
You should simply unset using the right key :
if (in_array($field_id, $ids))
unset($ids[array_search($field_id, $ids)]);
If you want to remove the element from the array, shouldn't you 'splice' it out instead with array_splice?
From the PHP manual: http://php.net/manual/en/function.array-splice.php
Your foreach wont make any changes since a copy of array is used.. you will need to use pass by reference in order for this to work. one of the way is mentioned below
while(list($key,$value) = each($array)){
if(your reason to unset)
unset($array[$key]);
}
this will remove the element from the array.
Suppose I have a multi-dimensional array with 100's of sub-arrays. The sub-arrays always have at least 3 indexes, but can have more. I'd like to remove from the big array all the sub-arrays which are duplicates of others in regards to those three indexes. Example with an array that only has two sub-arrays:
array(array(0 => 'a', 1=> 'b', 2 => 'c', 3 => 'd'), array(0 => 'a', 1=> 'b', 2=> 'c', 3=> 'z'))
one of the sub-arrays would be removed, because the first 3 indexes match even though the 4th does not.
I'm looking for the most elegant/efficient solution.
/**
* Create Unique Arrays using an md5 hash
*
* #param array $array
* #return array
*/
function arrayUnique($array, $preserveKeys = false)
{
$arrayRewrite = array();
$arrayHashes = array();
foreach($array as $key => $item) {
$hash = md5(serialize($item));
if (!isset($arrayHashes[$hash])) {
$arrayHashes[$hash] = $hash;
if ($preserveKeys) {
$arrayRewrite[$key] = $item;
} else {
$arrayRewrite[] = $item;
}
}
}
return $arrayRewrite;
}
$uniqueArray = arrayUnique($array);
var_dump($uniqueArray);
FROM: http://www.phpdevblog.net/2009/01/using-array-unique-with-multidimensional-arrays.html
Removed comments to give people incentive to visit site - I've used this on a few occasions.
Hope that helps!
EDIT: although not a solution to this particular problem in that you require matching the first 3 indexes, it is still nontheless a very good solution to the general question: how do I use array_unique() on a multidimensional array.
If somebody could pop along and edit for your purposes, all the better!
Zenph gets it 90% right, but he wanted to only look at the first 3 elements as unique. You can use the function below in conjunction with Zenph's code right before the serialize to only look at the first three elements.
function firstThree($array)
{
$retArray = array();
array_push($retArray, $array[1], $array[2], $array[3]);
return $retArray;
}
This will do the trick. Not the most elegant example due to the free function with a static variable, but you can make it more elegant by using a lambda or an instance of a class for the callback target.
function filter($subArray) {
static $seenKeys = null;
if ($seenKeys === null) {
$seekKeys = array();
}
// I 'm just selecting the "three first" indexes here,
// you can change it to better suit your needs
$thisKey = serialize(array_slice($subArray, 0, 3));
if (isset($seenKeys[$thisKey])) {
return false;
}
else {
return $seenKeys[$thisKey] = true;
}
}
$result = array_filter($inputArray, 'filter');
I think this example is as fast as you can go in PHP without making assumptions about the type and/or values of the first three items in each subarray. If any such assumption can be made, then at the very least the serialize call can be replaced with something more appropriate. I imagine that this would speed up the process quite a bit.
I want to remove an element from a PHP array (and shrink the array size). Just looking at the PHP docs, it seems this can be done using array_slice() and array_merge()
so I am guessing (off the top of my head) that some combination of array_merge() and array_slice will work. However, array_slice() requires an index (not a key), so I'm not sure how to quickly cobble these functions together for a solution.
Has anyone implemented such a function before?. I'm sure it must be only a few lines long, but I cant somehow get my head around it (its been one of those days) ...
Actually, I just came up with this cheesy hack when writing up this question....
function remove_from_array(array $in, value) {
return array_diff($in, (array)$value);
}
too ugly? or will it work (without any shocking side effects)?
This functionality already exists; take a look at unset.
http://php.net/manual/en/function.unset.php
$a = array('foo' => 'bar', 'bar' => 'gork');
unset($a['bar']);
print_r($a);
output will be:
array(
[foo] => bar
)
There's the array_filter function that uses a callback function to select only wanted values from the array.
you want an unset by value. loop through the array and unset the key by value.
unset($my_array['element']);
Won't work?
This code can be replaced by single array_filter($arr) call
foreach($array as $key => $value) {
if($value == "" || $value == " " || is_null($value)) {
unset($array[$key]);
}
}
/*
and if you want to create a new array with the keys reordered accordingly...
*/
$new_array = array_values($array);