1

I am passing an array via $_POST method. I want to eliminate the spaces from the index values. My array is

Array
(
    [full_word] => hi there
    [btn] => 
) 

I want to eliminate the space from the index element of full_word so that I can get the array below:

Array (
  [0]=> hi
  [1]=> there
)

But explode function is not working in here as $_POST returns an array and explode simply doesn't work on arrays.

What's the solution?

1
  • loop your array and then explode each full word Commented Feb 17, 2018 at 16:00

3 Answers 3

2

You can explode() around " " using array_walk. Eg below:

$arr = [ "full_word" => "hi there", "btn" => "" ];

// explode each value of array around " "
array_walk($arr, function(&$v) {
    $v = explode(" ", $v);
});

print_r($arr); 
// Array ( [full_word] => Array ( [0] => hi [1] => there ) [btn] => Array ( [0] => d ) )

Read more:

Sign up to request clarification or add additional context in comments.

Comments

1

Use the below code to explode only 'full_word' section of $_POST array,

$full_word_array = explode(" ",$_POST['full_word']); var_dump($full_word_array);

Comments

0

Actually, @AniketSahrawat answer is perfectly OK, but if you want to maintain immutability, you can use array_map and explode:

$result = array_map(function ($item) {
    return strpos($item, ' ') === false
        ? $item
        : explode(' ', $item);    
}, $array);

Here is the demo.

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.