This is my code.
if(in_array("1", $mod)){
$res=array('First Name','Insertion','Last Name','Lead Country');}
if(in_array("2", $mod)){
$res=array('Landline No:','Mobile No:','Lead Country');}
if(in_array("3", $mod)){
$res=array('City','State','Country','Lead Country');}
if(in_array("4", $mod)){
$res=array('Email','Lead Country');}
return $res;
Upto this it works fine. But if the array contains more than one value say (1,3) I need to return both results of 1 and 3.
eg: if the array is like this
array([0]=>1 [1]=>3)
then
$res=array('First Name','Insertion','Last Name','City','State','Country','Lead Country')
But if there are 2 lead country only one should be displayed how to do this? Pls help me.
Here's an example that uses a function to add the elements, only if they don't already exist:
function addItems($items, $arr)
{
foreach($items as $value)
{
if(!in_array($value, $arr))
{
$arr[] = $value;
}
}
return $arr;
}
$res = array();
if(in_array("1", $mod)){
$res = addItems(array('First Name','Insertion','Last Name','Lead Country'), $res);}
if(in_array("2", $mod)){
$res = addItems(array('Landline No:','Mobile No:','Lead Country'), $res);}
if(in_array("3", $mod)){
$res = addItems(array('City','State','Country','Lead Country'), $res);}
if(in_array("4", $mod)){
$res = addItems(array('Email','Lead Country'), $res);}
return $res;
Here's another way of doing it which is more OOP and is probably a bit more logical because it doesn't keep passing the whole array back and to, instead it uses an object which holds the array, and has a method to add to it, and get the final result:
class ItemsManager
{
protected $items = array();
public function addItems($items)
{
foreach($items as $value)
{
if(!in_array($value, $this->items))
{
$this->items[] = $value;
}
}
}
public function getItems()
{
return $this->items;
}
}
$im = new ItemsManager();
if(in_array("1", $mod)){
$im->addItems(array('First Name','Insertion','Last Name','Lead Country'));}
if(in_array("2", $mod)){
$im->addItems(array('Landline No:','Mobile No:','Lead Country'));}
if(in_array("3", $mod)){
$im->addItems(array('City','State','Country','Lead Country'));}
if(in_array("4", $mod)){
$im->addItems(array('Email','Lead Country'));}
return $im->getItems();
Use array_merge
:
$res = array();
if(in_array("1", $mod)){
$res=array_merge($res, array('First Name','Insertion','Last Name','Lead Country'));
}
// and so on ...
return $res;
Use array_merge to build the result...
$res = array();
if(in_array("1", $mod)) {
$res = array_merge($res, array('First Name','Insertion','Last Name','Lead Country'));
}
// etc