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 ?
use unset
.
foreach($a_input as $key => $val){
if($a_input[$key]==1) unset($a_input[$key]);
}
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);
}
You can use
$array = array(1,2,3,4,5);
if (($key = array_search('1', $array)) !== false) {
unset($array[$key]);
}
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
.
<?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
)
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;
});
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.