Created
January 17, 2019 12:07
-
-
Save kobus1998/8603cb0b8fc61a0109635206427cd5b5 to your computer and use it in GitHub Desktop.
Implode assoc
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 | |
/** | |
* @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