Skip to content

Instantly share code, notes, and snippets.

@wpscholar
Created October 4, 2016 14:52
Show Gist options
  • Save wpscholar/8dd9471d578c7f74a7709f05d4f9b5fa to your computer and use it in GitHub Desktop.
Save wpscholar/8dd9471d578c7f74a7709f05d4f9b5fa to your computer and use it in GitHub Desktop.
Set a value on an multidimensional array using dot notation in PHP
<?php
/**
* Set a value on an multidimensional array using dot notation
*
* @param array $data
* @param string $key
* @param mixed $value
*
* @return mixed
*/
function set_value( $data, $key, $value ) {
$indexes = explode( '.', $key );
$last_index = $indexes[ count( $indexes ) - 1 ];
$index = array_shift( $indexes );
if ( $index === $last_index ) {
$data[ $index ] = $value;
} else {
if ( ! array_key_exists( $index, $data ) ) {
$data[ $index ] = array();
}
$data[ $index ] = set_value( $data[ $index ], join( '.', $indexes ), $value );
}
return $data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment