0

I have one array that has values of arr1 = [1,2,3] and what I want to do is that 1,2,3 will store to another array with single index just like this arr 2 = [123] because this arr 2 will the one that I will store to the database.

my code is this

if($bul == "true"){
            while ($ai < count($sentencearr)){
                for($i = 0; $i<count($alpha); $i++){
                    if($sentencearr[$ai] == $alpha[$i]){
                        $answer[$ai] = $choicearray[$i];
                        $ia = count($alpha) + 1;
                    }else if($sentencearr[$ai] == $alphaup[$i]){
                        $answer[$ai] = $choicearrayup[$i];
                        $ia = count($alpha)+1;
                    }
                }
                $insert_arry = join($answer[$ai]);
                $sql = "insert into message(msg, name) values ('$insert_arry[$ai]', '$name')";
                $result=$conn->query($sql);
                header("Location:home.php");
                $ai++;
            }
2
  • If you store it like that, then it's a string? Or do you mean one array with one item that is a string of all items in arr1 combined without delimiter? Commented May 12, 2019 at 11:46
  • Possible duplicate of Merge array items into string. Perhaps not a perfect match, but $arr2[] = implode() is close enough to make it duplicate Commented May 12, 2019 at 11:47

1 Answer 1

0

Since you want to create a String from an Array you could simply use implode. Implode allows you to separate your array by any character you define. In your case you don't want to seperate it so you can leave it away. As a last step you will need to put the string back intro an array.

This looks like this:

$arr1 = [1, 2, 3];
$arr2 = [ implode($arr1) ];
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks I will try it
@Ana That's what the code above does. But in order to achieve this, you could also just create a multidimensional array: $arr2 = array( 'index-1' => $arr1 )
but how I will do that inside the looping? my code is like this
$exam = [implode($answer[$ai])]; $ai++; } $sql = "insert into message(msg, name) values ('$exam', '$name')"; $result=$conn->query($sql); header("Location:home.php");
Where is the loop? The above code works for what you asked for. Sry I can't help you with this one. Please update your question with all the code which is mandatory to understand the problem. THX.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.