Skip to content

Instantly share code, notes, and snippets.

@jdiglesias
Created November 11, 2018 09:54
Show Gist options
  • Save jdiglesias/b5e3f34d5b2a9d589a8a882dd15fb56e to your computer and use it in GitHub Desktop.
Save jdiglesias/b5e3f34d5b2a9d589a8a882dd15fb56e to your computer and use it in GitHub Desktop.
Find value within Drupal 8 render array
<?php
/**
* I got tired of clicking through render arrays displayed in Kint looking for a
* specific string. So I wrote this function to find all instances of that string
* and give me back a copy-pasteable index for each location.
*
* @param $str The string you're searching for
* @param $arr A Drupal 8 Render array
* @return array Strings representing PHP array indices that contain your string within $arr
*/
function find_str_in_render_arr($str, $arr){
$ret = array();
foreach($arr as $key => $val){
if(is_string($key)){
$left = "['";
$right = "']";
}
else{
$left = "[";
$right = "]";
}
if(is_array($val)){
$recur = find_str_in_render_arr($str, $val);
foreach($recur as $found_str_keys){
$ret[] = $left . $key . $right . $found_str_keys;
}
}
else if($str === $val ||
($val instanceof Drupal\Core\StringTranslation\TranslatableMarkup &&
$str == $val->render())){
$ret[] = $left . $key . $right;
}
}
return $ret;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment