0

I'm trying to concatenate array keys (which are originally a class properties). So what I did is:

echo '<pre>'.print_r(array_keys(get_object_vars($addressPark)),TRUE).'</pre>';

Outputs:

Array
(
    [0] => streetAddress_1
    [1] => street_address_2
    [2] => city_name
    [3] => subdivision_name
    [4] => country_name
)

This is how I get the AddressPark object's properties names.

$arr = array_keys(get_object_vars($addressPark));
$count = count($arr);

I want to access the object properties by index, that is why I used array_keys.

$props = str_repeat("{$arr[$count-$count]},",$count-2).$arr[$count-1];
echo $props;

The results is:

streetAddress_1,streetAddress_1,streetAddress_1,country_name

It repeats $arr[0] = 'streetAddress_1' which is normal because in every loop of the str_repeat the index of $arr is $count-$count = 0. So what I exactly want str_repeat to do is for each loop it goes like: $count-($count-0),$count-($count-1) ... $count-($count-4). Without using any other loop to increment the value from (0 to 4).

So is there another way to do it?

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87

1 Answers1

0

No, you cannot use str_repeat function directly to copy each of the values out of an array into a string. However there are many ways to achieve this, with the most popular being the implode() and array_keys functions.

array_keys extracts the keys from the array. The following examples will solely concentrate on the other part of the issue which is to concatenate the values of the array.

Implode

implode: Join array elements with a string

string implode ( string $glue , array $pieces )

Example:

<?php
$myArray = ['one','two','three'];

echo implode(',', $myArray); 
// one,two,three

echo implode(' Mississippi;', $myArray); 
// one Mississippi; two Mississippi; three Mississippi;

Foreach

foreach: The foreach construct provides an easy way to iterate over arrays, objects or traversables.

foreach (array_expression as $key => $value)
    ...statement...

Example:

<?php
$myArray = ['one','two','three'];
$output = '';
foreach ($myArray as $val) {
    $output .= $val . ',';
}
echo $output;
// one,two,three,

Notice that on this version we have an extra comma to deal with

<?php
echo rtrim($output, ',');
// one,two,three

List

list: Assign variables as if they were an array

array list ( mixed $var1 [, mixed $... ] )

Example:

<?php
$myArray = ['one','two','three'];
list($one, $two, $three) = $myArray;
echo "{$one}, {$two}, {$three}";
// one, two, three

Note that on this version you have to know how many values you want to deal with.


Array Reduce

array_reduce: Iteratively reduce the array to a single value using a callback function

mixed array_reduce ( array $array , callable $callback [, mixed $initial = NULL ] )

Example:

<?php
$myArray = ['one', 'two', 'three'];
echo array_reduce($myArray, function ($carry, $item) {
    return $carry .= $item . ', ';
}, '');
// one, two, three,

This method also causes an extra comma to appear.


While

while: while loops are the simplest type of loop in PHP.

while (expr)
    ...statement...

Example:

<?php
$myArray = ['one', 'two', 'three'];
$output = '';
while (!empty($myArray)) {
    $output .= array_shift($myArray);
    $output .= count($myArray) > 0 ? ', ' : '';
}
echo $output;
// one, two, three

Notice that we've handled the erroneous comma in the loop. This method is destructive as we alter the original array.


Sprintf and String Repeat

sprintf: My best attempt of actually using the str_repeat function:

<?php
$myArray = ['one','two','three'];
echo rtrim(sprintf(str_repeat('%s, ', count($myArray)), ...$myArray), ', ');
// one, two, three

Notice that this uses the splat operator ... to unpack the array as arguments for the sprintf function.


Obviously a lot of these examples are not the best or the fastest but it's good to think out of the box sometimes.

There's probably many more ways and I can actually think of more; using array iterators like array_walk, array_map, iterator_apply and call_user_func_array using a referenced variable.

If you can think of any more post a comment below :-)

R. Chappell
  • 1,184
  • 6
  • 17