FarFar
FarFar

Reputation: 141

Converting an array to a string without using the implode() function

Suppose I have an array that looks like this:

Array
(
    [0] => Model Number
    [1] => 987
    [2] => Interface
    [3] => 987
    [4] => GPU
    [5] => 98
    [6] => Core Clock
    [7] => 79
    [8] => Boost Clock
    [9] => 87
    [10] => CUDA Cores
    [11] => 987
 )

I want to concatenate it so it takes this format AND is a string:

Array {
   Model Number: 987;
   Interface: 987;
   GPU: 98;
   Core Clock: 79;
   ... And so on ...
}

The implode function doesn't really suit this because I need a ; after every 2 indexes. All my attempts to use a loop have failed. (Undefined Index and Out of memory errors)

Thanks in advance for any help!

Upvotes: 1

Views: 2171

Answers (4)

Sofiene Djebali
Sofiene Djebali

Reputation: 4508

This should work :

$specs = [];
$count = count($array);
for ($i = 0; $i < $count; $i+=2) {
    $specs[] = $array[$i] . ': ' . $array[$i + 1];
}

This will output :

array(6) {
  [0]=>
  string(17) "Model Number: 987"
  [1]=>
  string(14) "Interface: 987"
  [2]=>
  string(7) "GPU: 98"
  [3]=>
  string(14) "Core Clock: 79"
  [4]=>
  string(15) "Boost Clock: 87"
  [5]=>
  string(15) "CUDA Cores: 987"
}

EvalIn

Upvotes: 1

AbraCadaver
AbraCadaver

Reputation: 79014

Here's a simple way. Just chunk the array into 2 elements each chunk and use those 2 in your string:

$string = "";

foreach(array_chunk($array, 2) as $value) {
    $string .= "{$value[0]}: {$value[1]};\n";
}

Upvotes: 4

<?php

$array = Array
(
    0 => 'Model Number',
    1 => 987,
    2 => 'Interface',
    3 => 987,
    4 => 'GPU',
    5 => 98,
    6 => 'Core Clock',
    7 => 79,
    8 => 'Boost Clock',
    9 => 87,
    10 => 'CUDA Cores',
    11 => 987
 );

 $imploded = array_map(function ($a) {
   return implode($a, ': ');
 }, array_chunk($array, 2));


 print_r($imploded);

Upvotes: -1

Chin Leung
Chin Leung

Reputation: 14941

Suppose this is your array

$array = array(
    'Model Number',
    987,
    'Interface',
    987,
    'GPU',
    98,
    'Core Cloc',
    79,
    'Boost Clock',
    87,
    'CUDA Cores',
    987
);

You can loop through the list and make a new array

$result = array();
foreach($array as $key => $value)
    if($key % 2 == 0) // Every two index
        $result[$key] = $value . ": ";
    else if(isset($result[$key-1]))
        $result[$key-1] .= $value;

The result would be

array(6) {
  [0]=>
  string(16) "Model Number:987"
  [2]=>
  string(13) "Interface:987"
  [4]=>
  string(6) "GPU:98"
  [6]=>
  string(12) "Core Cloc:79"
  [8]=>
  string(14) "Boost Clock:87"
  [10]=>
  string(14) "CUDA Cores:987"
}

Upvotes: 1

Related Questions