This sounds so simple but for some reason its not working on my end. I have an array which will check if values exist then will act accordingly
My array contains values and my condition is meant to check 2 conditions if value "a" is contained in the array at array index 0 and "b" doesnt exist in array then do this. if value "a" at index 0 and "b" does exist then run another block of code.
//THIS CONTAINS ALL THE FIELDS SELECTED
$report_cols = $_POST['report_cols'];
$percent_amt= explode(",",$report_cols);
$n_fields_arr = array();
$b=0;
//This checks if b exists in array
if (array_key_exists('`b`', $percent_amt))
{
$b = 1;
}
if($percent_amt[0] == '`a`' && $b == 0)
{
$report_cols = str_replace("`a`,","",$report_cols);
$report_cols = str_replace(",`a`","",$report_cols);
$report_cols = str_replace(",,",",",$report_cols);
array_push($n_fields_arr,"a");
echo "done";
}
if($percent_amt[0] == '`a`' && $b == 1)
{
$report_cols = str_replace("`a`,","",$report_cols);
$report_cols = str_replace(",`a`","",$report_cols);
$report_cols = str_replace(",,",",",$report_cols);
$report_cols = str_replace("`b`,","",$report_cols);
$report_cols = str_replace(",`b`","",$report_cols);
$report_cols = str_replace(",,",",",$report_cols);
array_push($n_fields_arr,"a","b");
echo "Done AB";
}
Error I am having is that its not recongizing the two && section and keeps running the first if statement. If there is a something am missing or a better method your help will be grately appreciated
explode()
function explodes array with numeric keys.
use in_array()
to check b
.
if (in_array('b', $percent_amt))
{
$b = 1;
}
You can use strpos to search for an occurrence of a string within a string. And use an array for the search argument for str_replace. Which will simplify your code.
//$report_cols = $_POST['report_cols'];
$report_cols = '`a`,`foo`,`a`,`b`,`bar`,`b`,';
$n_fields_arr = array();
$b_found = strpos($report_cols, '`b`') !== false ? true : false;
$a_start = strpos($report_cols, '`a`') == 0 ? true : false;
if ($a_start) {
$report_cols = str_replace(array('`a`','`b`'), '', $report_cols);
$report_cols = trim(preg_replace('/,+/', ',', $report_cols), ',');
$n_fields_arr[] = 'a';
if ($b_found) {
$n_fields_arr[] = 'b';
}
}
print $report_cols;
var_dump($n_fields_arr);
Output:
`foo`,`bar`
array (size=2)
0 => string 'a' (length=1)
1 => string 'b' (length=1)