[英]i am having issues in array using foreach loop
I am getting three values("123","456","789") in array using foreach loop, now i want whenever i am getting value "456" then delete this value from array.how can i do this ? 我正在使用foreach循环在数组中获取三个值(“ 123”,“ 456”,“ 789”),现在我想每当我获取值“ 456”时从数组中删除该值。我该怎么办? i have tried if loop inside the array when i get 456 but it still not working.`
当我得到456时,我已经尝试过if循环在数组内,但是它仍然无法正常工作。
` `
A better way would be to use array_splice 更好的方法是使用array_splice
Then just create a function to wrap it [array_pluck], which plucks out the array item, and updates the original input. 然后,只需创建一个包装它的函数[array_pluck],即可提取数组项并更新原始输入。
<?php
$input = ["123","456","789"];
function array_pluck(&$array, $key) {
if (isset($array[$key])) {
return array_splice($array, $key, 1)[0];
}
}
echo array_pluck($input, 1); //456
print_r($input);
https://3v4l.org/J42A5 https://3v4l.org/J42A5
If you're looping over the array, and then you want to remove the items, you could also use a generator. 如果要遍历数组,然后要删除项目,则也可以使用生成器。
<?php
$input = ["123","456","789"];
function array_pluck_gen(&$array) {
foreach ($array as $k => $v) {
unset($array[$k]);
yield $v;
}
}
foreach (array_pluck_gen($input) as $value) {
echo $value;
}
print_r($input);
Or just unset it. 或者只是取消设置。
<?php
$input = ["123","456","789"];
foreach ($input as $key => $value) {
unset($input[$key]);
echo $value;
}
print_r($input);
You can do it like this: 您可以这样做:
$array = array("123","456","789") ;
$arrFinal = array();
array_walk($array, function($val, $key) use (&$arrFinal){
if ($val != '456') {
$arrFinal[$key] = $val;
}
});
print_r($arrFinal);
$array=array("123","456","789");
foreach($array as $key=>$val){
if($val=="456"){
unset($array[$key]);
}
}
print_r($array);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.