PHP 8.5.0 Alpha 2 available for testing

Voting

: five plus two?
(Example: nine)

The Note You're Voting On

op_adept at yahoo dot co dot uk
14 years ago
Prefix array values with keys and retrieve as a glued string, the original array remains unchanged. I used this to create some SQL queries from arrays.

<?php

function array_implode_prefix($outer_glue, $arr, $inner_glue, $prefix=false){
array_walk( $arr , "prefix", array($inner_glue, $prefix) );
return
implode($outer_glue, $arr);
}

function
prefix(&$value, $key, array $additional){
$inner_glue = $additional[0];
$prefix = isset($additional[1])? $additional[1] : false;
if(
$prefix === false) $prefix = $key;

$value = $prefix.$inner_glue.$value;
}

//Example 1:
$order_by = array("3"=>"ASC", "2"=>"DESC", "7"=>"ASC");
echo
array_implode_prefix(",", $order_by, " ");
//Output: 3 ASC,2 DESC,7 ASC

//Example 2:
$columns = array("product_id", "category_id", "name", "description");
$table = "product";

echo
array_implode_prefix(", ", $columns, ".", $table);
//Output:product.product_id, product.category_id, product.name, product.description

//Example 3 (function prefix) won't really be used on its own
$pre= "vacation";
$value = "lalaland";
prefix($value, $pre, array("."));
echo
$value;

//Output: vacation.lalaland

?>

<< Back to user notes page

To Top