November 7, 2012
PHP4 variables: concatenate array in declaration
Question by Dbugger
Possible Duplicate:
PHP error, concatenation in array() in member initialiser
I have this sort of code:
var $compSQL = array(
'0' => "#FIELD# LIKE '%#VALUE#%'",
'1' => "#FIELD# NOT LIKE '%#VALUE#%'",
'2' => "#FIELD# LIKE '#VALUE#%'",
'3' => "#FIELD# NOT LIKE '#VALUE#%'",
'4' => "#FIELD# LIKE '%#VALUE#'",
'5' => "#FIELD# NOT LIKE '%#VALUE#'",
'6' => "#FIELD# = '#VALUE#'",
'7' => "#FIELD# != '#VALUE#'"
);
and I need to change the values of the string with some concatenation operation, sorta like this:
var $compSQL = array(
'0' => "#FIELD# LIKE ".$somevalue,
...
);
But that is not allowed. How should I do it?
Answer by mmmshuddup
As requested, here is the bit of code that will help you run your concat operation.
public function myReplace($field, $value, $index = '0')
{
$patterns = array('/#FIELD#/', '/(%{0,1}#VALUE#%{0,1})/');
$replacements = array($field, $value);
$merged = preg_replace(
$patterns, $replacements, $this->compSQL[$index]
);
$this->compSQL[$index] = $merged;
}
Then say you set a field name and value in your code and call that function:
$field = 'user';
$value = 'test';
$object->myReplace($field, $value, '7');
Answer by Starx
You can directly insert the variable inside the double quotes.
'0' => "#FIELD# LIKE $somevalue",
Or
'0' => "#FIELD# LIKE {$someValue}",