March 12, 2013

Concatenating lang CONST and STR CONST in PHP

Question by Jorge

Trying to concatenate:

<?php
class MD_ImpFormularios extends CI_Model {
  private $dir_forms = __DIR__ . 'Hola';

Gives:

PHP Parse error:  syntax error, unexpected '.', expecting ',' or ';' in md_impformularios.php on line 3

But I don’t see anything wrong here, it isn’t a CONST or Static, it’s a simple variable.

Thanks

Answer by Starx

Do not do concatenation while declaring class variables.

private $dir_forms = __DIR__ . 'Hola';
                          // ^ This is NOT allowed during declaration

You can use your constructor function to set such variables.

private $dir_forms;
public function __construct() {
    $this -> dir_forms = __DIR__ . 'Hola';
}
March 10, 2012

How to handle my data?

Question by Jack4

Edit: The aim of my method is to delete a value from a string in a database.

I cant seem to find the answer for this one anywhere. Can you concatenate inside a str_replace like this:

str_replace($pid . ",","",$boom);
  • $pid is a page id, eg 40
  • $boom is an exploded array

If i have a string: 40,56,12 i want to make it 56,12 however without the concatenator in it will produce:

,56,12

When i have the concat in the str_replace it doesnt do a thing. So does anyone know if you can do this?

Answer by hakre

After you have edited it becomes clear that you want to remove the value of $pid from the array $boom which contains one number as a value. You can use array_search to find if it is in at if in with which key. You can then unset the element from $boom:

$pid = '40';
$boom = explode(',', '40,56,12');
$r = array_search($pid, $boom, FALSE);
if ($r !== FALSE) {
    unset($boom[$r]);
}

Old question:

Can you concatenate inside a str_replace like this: … ?

Yes you can, see the example:

$pid = '40';
$boom = array('40,56,12');
print_r(str_replace($pid . ",", "", $boom));

Result:

Array
(
    [0] => 56,12
)

Which is pretty much like you did so you might be looking for the problem at the wrong place. You can use any string expression for the parameter.

It might be easier for you if you’re unsure to create a variable first:

$pid = '40';
$boom = array('40,56,12');
$search = sprintf("%d,", $pid);
print_r(str_replace($search, "", $boom));

Answer by Starx

As $boom is an array, you don’t need to use array on your case.

Change this

$boom = explode(",",$ticket_array);
$boom = str_replace($pid . ",","",$boom);
$together = implode(",",$boom);

to

$together = str_replace($pid . ",","",$ticket_array);

Update: If you want still want to use array

$boom = explode(",",$ticket_array);
unset($boom[array_search($pid, $boom)]);
$together = implode(",",$boom);
...

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