0

I have an array.

$a_input = array(1,2,3,4,5)

I want to remove 1 from array . out put is :

array(2,3,4,5);

remove 2 => output:

array(1,3,4,5);

remove 3 => output :

array(1,2,4,5);

..... how to do this with for loop ?

Doan Tran
  • 58
  • 4

6 Answers6

0

use unset.

foreach($a_input as $key => $val){
   if($a_input[$key]==1) unset($a_input[$key]); 
}
red
  • 117
  • 1
  • 11
0

try this

$a_input = array(1,2,3,4,5);

$cnt=count($a_input);
for($i=0;$i<$cnt;$i++){
   $remove = array($i+1);
   $output1=array_diff($a_input,$remove);
   var_dump("<pre>",$output1);
}

Online test

ashkufaraz
  • 5,179
  • 6
  • 51
  • 82
0

You can use

$array = array(1,2,3,4,5);
if (($key = array_search('1', $array)) !== false) {
unset($array[$key]);
}
Nishant Nair
  • 1,999
  • 1
  • 13
  • 18
0

Here we are searching a value in the array If it is present, then proceed to get the key at which required value is present, then unseting that value.

Try this code snippet here

<?php
ini_set('display_errors', 1);

$a_input = array(1,2,3,4,5);
$numberToSearch=2;

if(in_array($numberToSearch,$a_input))//checking whether value is present in array or not.
{
    $key=array_search($numberToSearch, $a_input);//getting the value of key.
    unset($a_input[$key]);//unsetting the value
}
print_r($a_input);

Output:

Array
(
    [0] => 1
    [2] => 3
    [3] => 4
    [4] => 5
)
Sahil Gulati
  • 15,028
  • 4
  • 24
  • 42
0

What you need is array_filter:

$input = array(1,2,3,4,5)
$remove = 1;
$result = array_filter($input, function ($val) use ($remove) {
  return $val !== $remove;
});
xdazz
  • 158,678
  • 38
  • 247
  • 274
0

You need array_diff.

$a_input = array(1,2,3,4,5);

you can create new array with values like below:

$remove = array(1,2);

$result=array_diff($a_input,$remove);

output:

array(3,4,5);

Most of the programmer use this way only.And this will work for multiple elements also.

lalithkumar
  • 3,480
  • 4
  • 24
  • 40