Created
October 4, 2016 14:52
-
-
Save wpscholar/8dd9471d578c7f74a7709f05d4f9b5fa to your computer and use it in GitHub Desktop.
Set a value on an multidimensional array using dot notation in PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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