How to output an array of $ arr all but 2

$var = "2"; $arr = array("1"=>"1", "2"=>"2", "3"=>"3"); 

expected result:

 1 3 
  • Meaning the value or key of the array? - Alliswell
  • let's say that the key would be output - Yuri
  • take a look at my answer. - Alliswell

3 answers 3

as an option

 unset($arr[$var]); 

if with search

 $key = array_search($var, $arr); if ($key !== false) { unset($arr[$key]); } 
  • thanks, this is what you need) - Yuri
  • It's not entirely clear why delete keys if you can just exclude them) - Alliswell
  • use cycle bad practice. If you need to have the original array, you always wash your copy with it - username

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; } } 
  • So it’s okay, although the first version of the identity is good - Yuri

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"; }