Array keys / values flatten

Hello,

I have the following array:


$array = array(
  'key one',
  'key two',
  'key tree' => array()
);

How to flatten it so that I would get this:

array(‘key one’, ‘key two’, ‘key tree’);

The problem is that the first two elements become values, and the third becomes key. How to get all keys // values like in the example above?

There must be some simplified php function to do this, but I cannot seem to find it!

Thanks for help!

[fphp]array_keys[/fphp]. :slight_smile:

I’m sure there are more elegant solutions, but this should work:


<?php

$array = array(
  'key one',
  'key two',
  'key tree' => array()
);

$result = array();

foreach($array as $key => $value) {
    if(is_array($value)) {
        $result[] = $key;
    } else {
        $result[] = $value;
    }
}

var_dump($result);

?>

This snippet of code will fail miserably though if the value for an entry isn’t an array (e.g. ‘key three’ => ‘value three’ will fail).

@Anthony, I thought that too, but array_keys gives:


array ( 
   0 => 0, 
   1 => 1, 
   2 => 'key tree'
)

Gah, of course it does. :blush:

I would probably only change your solution slightly to:-


<?php
$array = array(
  'key one',
  'key two',
  'key tree' => array()
);

$keys = array();

foreach($array as $key => $value){
  $keys[] = ctype_digit($key) ? $value : $key ;
}


I’m assuming that you wanted only 1 level of keys/values. In which case Anthony’s code works absolutely fine.

My mind of course jumped ahead a thread, and responded to ‘but i havent really flattened it if there is something inside that array up there’… so… I tweaked it :smiley: Go go recursion.


$output = flatten($mybigarray);

function flatten($array) {
$keys = array();
foreach($array as $key => $value){ 
  if(is_array($value)) {
    $keys = array_merge($keys,flatten($value));
  } elseif(is_numeric($key) {
    $keys[] = $value;
  } else {
    $keys[] = $key;
  }
  return $keys;
}

Can I play?

$array1 = array(
  'key one',
  'key two',
  'key three' => array()
);

$keys = array_keys( $array1 );
$vals = array_values( $array1 );
$a = array();

foreach( array_merge( $keys, $vals)  as $v)
  if( is_string($v) ) $a[] = $v;

var_dump( $a );

// array
//  0 => string 'key three' (length=9)
//  1 => string 'key one' (length=7)
//  2 => string 'key two' (length=7)