koe
koe

Reputation: 746

php how to cut array and add other charactor to it

I have an array like :

Array
(
  [0] => a
  [1] => b
  [2] => c
  [3] => d
  [4] => e
  [5] => f
  [6] => g
  [7] => h
) 

And I want add semicolon(;) every 3 index value and it's read from end of array that result is string like "ab;cde;fgh";

Upvotes: 2

Views: 67

Answers (5)

airtech
airtech

Reputation: 496

This works... there's a couple different ways to do this. This was the quickest way off the top of my head without using a second array.

$vars = array("a","b","c","d","e","f","g","h");
print_r(insert_char($vars));

function insert_char($Array, $Delimeter=";", $Count=3) {
    for ($i = sizeOf($Array) - $Count; $i > 0; $i -= $Count) 
        array_splice($Array, $i, 0, $Delimeter);

    return implode($Array);
}

Result

ab;cde;fgh

Upvotes: 1

Kevin
Kevin

Reputation: 41873

Its an odd way, but since you want it reversed you may need to use some function here:

$array = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h');
$array = array_reverse($array); // reverse it
$array = array_chunk($array, 3); // cut by threes
$string = '';
foreach ($array as $value) {
    $string .= implode($value); // glue them
    if(count($value) == 3) { // if still three, add a semi
        $string .= ';';
    }
}
$string = strrev($string); // then reverse them again
echo $string; // ab;cde;fgh

Upvotes: 1

Mark Miller
Mark Miller

Reputation: 7447

Here's a fun, and kind of obnoxious, one-liner:

$str = ltrim(strrev(chunk_split(implode(array_reverse($arr)), 3, ';')), ';');

Example:

$arr = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h');
$str = ltrim(strrev(chunk_split(implode(array_reverse($arr)), 3, ';')), ';');
echo $str; //ab;cde;fgh

// More sample output based on different input arrays:
$arr = array('a', 'b', 'c', 'd', 'e'); //ab;cde
$arr = array('a', 'b', 'c', 'd', 'e', 'f'); //abc;def
$arr = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k'); //ab;cde;fgh;ijk

See demo

Upvotes: 1

Heroselohim
Heroselohim

Reputation: 1291

Just traversing it from backward and joining the string in reverse too gives that result.

$vars = array("a","b","c","d","e","f","g");
$c = 0; $s = "";
for ($i = sizeof($vars)-1; $i >= 0; $i--)
{
    $c++;
    $s = $vars[$i].$s;
    if ($c == 3) { $c = 0; $s = ";".$s; }
}

echo $s;

Upvotes: 0

ThatOneDude
ThatOneDude

Reputation: 1526

Here's my solution, although it feels inefficient it is pretty clear:

<?php
$myarr=Array('a','b','c','d','e','f','g','h');
$newarr=Array();
$arrsize = sizeof($myarr);
for ($x = 0, $i = 0; $x < $arrsize; $x++, $i++) {
    $newarr[$i] = $myarr[$arrsize - $x - 1];
    if (($arrsize - $x) % 3 == 0) {
        $i++;
        $newarr[$i] = ";";      
    }
}
$newarr = array_reverse($newarr);
print_r($newarr);
?>

Upvotes: 0

Related Questions