Skip to content

Instantly share code, notes, and snippets.

@kobus1998
Created January 17, 2019 12:07
Show Gist options
  • Save kobus1998/8603cb0b8fc61a0109635206427cd5b5 to your computer and use it in GitHub Desktop.
Save kobus1998/8603cb0b8fc61a0109635206427cd5b5 to your computer and use it in GitHub Desktop.
Implode assoc
<?php
/**
* @param string|array
* @param string|array
* @param string
*/
function implodeAssoc($glue, $arr, $key = null)
{
if (is_array($l)) {
$key = $arr;
$arr = $glue;
$l = '';
}
$s = "";
foreach($arr as $val) {
if (!isset($val[$key])) continue;
$s .= $val[$key] . $glue;
}
$s = rtrim($s, $glue);
return $s;
}
// without glue
echo implodeAssoc([
['text' => 'a'],
['text' => 'b'],
['text' => 'c'],
], 'text'); // abc
// with glue
echo implodeAssoc(',', [
['id' => 1],
['id' => 2],
['id' => 3],
], 'id'); // 1,2,3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment