Reputation: 2763
I have a conditional string like this:
echo $cnd = "'use_funds'=>'no'";
And my $data
array is :
$data = array(
$cnd,
'quantity' => $_POST['qty_' . $q],
'veg_name' => $_POST['veg_name_' . $q],
'rate' => $_POST['rate_' . $q],
'ws_price' => $_POST['ws_price_' . $q],
'ret_price' => $_POST['ret_price_' . $q],
'mop' => $_POST['mop_' . $q],
'ret_margin' => $_POST['ret_margin_' . $q]
);
The above echo $cnd
shows 'use_funds'=>'no'
, but the var_dump($data)
shows array
0 => string ''use_funds'=>'no'' (length=17)
. And since its a string my data is not inserting in my table. How can I make the $cnd
to a associative array element instead of string?
Upvotes: 1
Views: 4849
Reputation: 1191
If it must be a string, split it and add it to the array. http://php.net/manual/en/function.explode.php
The explode function takes a string and breaks it into an array
$my_string_split = explode('=>', $cnd);
// returns [0 => 'use_funds', 1 => 'no']
$data[$my_string_split[0]] = $my_string_split[1];
If it does not need to be a string, do it literally:
$data['use_funds'] = 'no';
Upvotes: 1
Reputation: 6701
echo $cnd = "'use_funds'=>'no'";
The above line considers "'use_funds'=>'no'"
as a string and assigns it to $cnd
. So no matter what, it always remains as a string unless you make any proper change to it. The default key in that case will be 0
. So, it will be like:
[0] => "'use_funds'=>'no'"
To get around this problem, you can do this:
$cnd = array('use_funds'=>'no');
Then, you an use array_merge() function to merge the two like this:
array_merge($cnd, $data);
Upvotes: 0
Reputation: 2540
first of all your $cnd
is string , not an array. and you are trying to append this $cnd
with $data
array.
for adding element to an array we basically use push()
method. For your case if you use array_push
method then you will get a output like below
array_push($cnd,$data);
$data=array(
0=>'use_funds'=>'no',
'quantity'=>$_POST['qty_'.$q],
'veg_name'=>$_POST['veg_name_'.$q],
'rate'=>$_POST['rate_'.$q],
'ws_price' => $_POST['ws_price_'.$q],
'ret_price' => $_POST['ret_price_'.$q],
'mop' => $_POST['mop_'.$q],
'ret_margin' =>$_POST['ret_margin_'.$q]
);
so my suggession will be if you want you desire result then follow below step:-
either define your $cnd as an array and then use array_merge();
Upvotes: 0
Reputation: 13535
You can accomplish it using eval
$cnd = "'use_funds'=>'no'";
eval("\$x = array($cnd);");
print_r($x);
Upvotes: -1
Reputation: 15603
don't use the $cnd part to make and insert the data in the array:
Use the below code:
$data['use_funds'] = 'no';
And this code will append the array. OR you can use the array_push function of PHP.
Upvotes: 2
Reputation: 3925
if (your condition) {
$data['use_funds'] = 'no';
} else {
//some other code
}
Upvotes: 3