Tuesday, 17 May 2016

How to delete an array elements?

How to delete an array elements?

Question: How to delete an array element based on key?
$arrayData = array(0=>'one',1=>'two',3=>'three',4=>'four',5=>'five',6=>'six'); 
print_r($arrayData); echo "
";
/*
 * Array ( [0] => one [1] => two [3] => three [4] => four [5] => five [6] => six ) 
 */
unset($arrayData[4]);


print_r($arrayData);
/**
Array ( [0] => one [1] => two [3] => three [5] => five [6] => six ) 
 * 
 */



Question: How to delete multiple array element?
$arrayData = array(0=>'one',1=>'two',3=>'three',4=>'four',5=>'five',6=>'six'); 
print_r($arrayData); echo "
";
/*
 * Array ( [0] => one [1] => two [3] => three [4] => four [5] => five [6] => six ) 
 */
array_splice($arrayData, 1,2);


print_r($arrayData);
/**
Array ( [0] => one [1] => four [2] => five [3] => six ) 
 * 
 */



Question: How to replace multiple array element with single array?
$arrayData = array(0=>'one',1=>'two',3=>'three',4=>'four',5=>'five',6=>'six'); 
print_r($arrayData); echo "
";
/*
 * Array ( [0] => one [1] => two [3] => three [4] => four [5] => five [6] => six ) 
 */
array_splice($arrayData, 1,2,array('r'=>'replaced'));


print_r($arrayData);
/**
Array ( [0] => one [1] => replaced [2] => four [3] => five [4] => six ) 
 * 
 */



Question: How to delete First element of an array?
$arrayData = array(0=>'one',1=>'two',3=>'three',4=>'four',5=>'five',6=>'six'); 
print_r($arrayData); echo "
";
/*
 * Array ( [0] => one [1] => two [3] => three [4] => four [5] => five [6] => six ) 
 */
array_shift($arrayData);


print_r($arrayData);
/**
Array ( [0] => two [1] => three [2] => four [3] => five [4] => six ) 
 * 
 */



Question: How to delete Last element of an array?
$arrayData = array(0=>'one',1=>'two',3=>'three',4=>'four',5=>'five',6=>'six'); 
print_r($arrayData); echo "
";
/*
 * Array ( [0] => one [1] => two [3] => three [4] => four [5] => five [6] => six ) 
 */
array_pop($arrayData);


print_r($arrayData);
/**
Array ( [0] => one [1] => two [3] => three [4] => four [5] => five ) 
 * 
 */