How to output an array of $ arr all but 2
$var = "2"; $arr = array("1"=>"1", "2"=>"2", "3"=>"3"); expected result:
1 3 "1", "2"=>"2", "3"=>"3"); expected resu...">
as an option
unset($arr[$var]); if with search
$key = array_search($var, $arr); if ($key !== false) { unset($arr[$key]); } If you exclude an array key:
foreach ($arr as $key => $item) { if ($key != 2) { echo $item; } } If you exclude the value of an array element:
foreach ($arr as $key => $item) { if ($item != 2) { echo $item; } } Here is an alternative option to do exactly what was voiced in the question: output the values of the array elements, except for the element with an arbitrary key. We do not know, maybe TSU will need the source array, then why delete the elements? :) The keys are replaced by letters, for clarity.
$sourceArray = ["a" => "1", "b" => "2", "c" => "3"]; // Короткий синтаксис доступен с 5.4 $ignoreKey = "b"; $filterFunc = function($key) use ($ignoreKey) { // Кроме ключа, в функции нам поднабится // внешняя переменная return $key != $ignoreKey; // Когда равняется True, // элемент массива "проходит" }; foreach (array_filter( $sourceArray, // Исходный массив $filterFunc, // Наша фильтрующая функция ARRAY_FILTER_USE_KEY // Фильтрация функцией происходит по ключу ) as $key => $value) { echo $value . "\n"; } Source: https://ru.stackoverflow.com/questions/437080/
All Articles