Gamer
Gamer

Reputation: 311

How to explode spaces from the index value of an array in PHP?

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?

Upvotes: 1

Views: 104

Answers (3)

Pradeep
Pradeep

Reputation: 74

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);

Upvotes: 1

Aniket Sahrawat
Aniket Sahrawat

Reputation: 12937

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:

Upvotes: 2

sevavietl
sevavietl

Reputation: 3812

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.

Upvotes: 0

Related Questions