2

i had a problem about returning an array into a spesified string. so, this is my code that i had been try.

$setValues = array("test1", "test2", "testurl");
$change = join("','", $setValues);    
$done = str_replace("", "?", $change);

so, the $change variable will return an array something like this :

'test1', 'test2', 'testurl'

i want to change that array into something like this :

?, ?, ?

is it possible to doing this?

3
  • Uh, what? Could you please clarify what you mean? You want to replace the text with question marks? Commented Oct 7, 2015 at 7:03
  • Just set all the values to ? !! Commented Oct 7, 2015 at 7:04
  • i know that one, but i got a situation that not allowing me to doing that methods, it's actually a function. Commented Oct 7, 2015 at 7:05

3 Answers 3

7

use array_map() with callback

    $setValues = array("test1", "test2", "testurl");
    $change = array_map(function($val) { return "?"; }, $setValues);
    $change = join(",", $change); 
    echo $change;// outputs => ?,?,?
Sign up to request clarification or add additional context in comments.

2 Comments

simple, and very straight forward. thanks Mr. Niranjan!
You can simply do it echo implode(',',array_map(function($val){ return "?";},$setValues));
0

This will work for you-

function myfunction($num)
{
   return '?';
}

$setValues = array("test1", "test2", "testurl");
$setValues = array_map("myfunction",$setValues);
$change = join("','", $setValues);    
$done = str_replace("", "?", $change);

2 Comments

this returns test1','test2','testurl
this one also working, awesome method. thanks Mr. Rohit!
0

Iterating with array_map seems way too overkill for this. You're basically trying to generate n questionmarks, given that n = count($array). So why not just:

$questionmarks = join( "," , array_fill( 0, count( $array ), "?" ) );

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.