Showing posts with label PHP IMPOLDE. Show all posts
Showing posts with label PHP IMPOLDE. Show all posts

Thursday, 30 August 2018

PHP - Fastest way to implode an associative array with keys

I'm looking for a fast way to turn an associative array in to a string. Typical structure would be like a URL query string but with customizable separators so I can use '&' for xhtml links or '&' otherwise.

My first inclination is to use foreach but since my method could be called many times in one request I fear it might be too slow.
<?php
$Amp = $IsXhtml ? '&amp;' : '&';
$Parameters = array('Action' => 'ShowList', 'Page' => '2');
$QueryString = '';
foreach ($Parameters as $Key => $Value)
        $QueryString .= $Amp . $Key . '=' . $Value;

Is there a faster way?

You can use http_build_query() to do that.
Generates a URL-encoded query string from the associative (or indexed) array provided.

PHP - How to correctly use implode () with associative arrays

 I have a question regarding the implode() in php, i have this array()

$user_data = array(
    'user_id_num' => $_POST['userid'],
    'fullname' => $_POST['userfname'],
    'username' => $_POST['useruname'],
    'password' => $password_hash
);

what i want to achieve is like this for example,
for the fields
`user_id_num`,`fullname`,`username`,`password`

and for the values
'2159','Sample Name','example','mypassword' <- hash password

what i have tried so far is this
$user_fields = '`' . implode('`, `', $user_data) . '`';
$user_data   = '\'' . implode('\', \', $user_data) . '\'';

but i can't get what i want to achieve can someone help me with this? thanks in advance

Try
$user_fields = '`' . implode('`, `', array_keys($user_data)) . '`';
$user_data   = "'" . implode("', '", array_values($user_data)) . "'";