2

I am using in_array() function and trim() in order to detect strings in my array that include parenthesis (). Although that my current program is operating and meets my needs I would like to take it to the next level and make it more generic. Currently I am specifying the array position through "stack[2]".

$stack = array( "test-1" , "test-2" , "(test-3)" );

print_r($stack);

if ( in_array( "".$stack[2]."" , $stack , TRUE ) ) {
  $stack[2] = trim($stack[2], '()');
}

print_r($stack);

Before the trimming process:

Array
(
    [0] => test-1
    [1] => test-2
    [2] => (test-3)
)

After the trimming process:

Array
(
    [0] => test-1
    [1] => test-2
    [2] => test-3
)

I would like my program to search each value in the array, remove the () and save it on the same position. Sample of a test array is provided below:

$stack = array( "test-1" , "test-2" , "(test-3)" , "test-4" , "(test-5)" );

I am sure there is a way but I can not figure it how to do it.

Thank you for your time and effort.

2

3 Answers 3

0

Use a for loop and sizeof array:

$stack = array( "test-1" , "test-2" , "(test-3)" , "test-4" , "(test-5)" );

print_r($stack);

for ($i = 0; $i < sizeof($stack); $i++){
   $stack[$i] = trim($stack[$i], '()');
}

print_r($stack);
0

At the end was extremely simple, I used foreach() and push the elements to a new array. So simple and the result as expected. Sample of code and output provided bellow:

$stack = array( "test-1" , "test-2" , "(test-3)" , "test-4" , "(test-5)" );

print_r($stack);

Output of print_r() before the loop:

Array
(
    [0] => test-1
    [1] => test-2
    [2] => (test-3)
    [3] => test-4
    [4] => (test-5)
)

$array = array();

foreach ($stack as $string) {
  $string = trim($string, '()');
  array_push($array, "".$string."");
}

print_r($array);

Output of the print_r() after the process:

Array
(
    [0] => test-1
    [1] => test-2
    [2] => test-3
    [3] => test-4
    [4] => test-5
)

Sorry for the so simple questions/answer.

0
$stack = array( "test-1" , "test-2" , "(test-3)" , "test-4" , "(test-5)" );

for(i=0; i < count($stack); i++) {
  $stack[$i] = trim($stack[$i], '()');
}

I would suggest going and reading some tutorials on PHP programming. This is a pretty basic idea.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.