user1876234
user1876234

Reputation: 857

Reduce an array element's value from a single-element array to the string value of the subarray element

I wonder if there's easy way to convert array which is in another array to string and keep it in that array ? The array which is inside array always consists of only 1 key. This is array that I have now:

array(6) {
  ["miestas"]=>
  string(2) "CC"
  ["checkbox"]=>
  array(1) {
    [0]=>
    string(1) "1"
  }
  ["kiekis"]=>
  string(5) "Three"
}

And this is the result what I want to get:

array(6) {
  ["miestas"]=>
  string(2) "CC"
  ["checkbox"]=>
  string(1) "1"
  ["kiekis"]=>
  string(5) "Three"
}

Upvotes: 0

Views: 73

Answers (4)

vee
vee

Reputation: 38645

Loops through the input array and checks if value is an array using is_array function. Pushes value array's value at index zero if an array otherwise pushes value to the result array.

$input = array('miestas' => 'CC', 'checkbox' => array("1"), 'kiekis' => 'Three');

$result = array();
foreach($input as $key=>$value) {
    $result[$key] = is_array($value) ? $value[0] : $value;  
}

// var_dump($result);

Upvotes: 1

underscore
underscore

Reputation: 6887

array_replace

$replacement = array('checkbox' => 1); 

$outputYouWant = array_replace($yourArray, $replacement);

print_r($outputYouWant);

Upvotes: 1

BlitZ
BlitZ

Reputation: 12168

Read this: http://php.net/array

Use this: $array['checkbox'] = $array['checkbox'][0];

Upvotes: 4

AlexP
AlexP

Reputation: 9857

You can type cast the value

$data['checkbox'] = (string) $data['checkbox'];

Upvotes: 2

Related Questions