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}",

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!