Home > Enterprise >  add values to values already existed in a php array
add values to values already existed in a php array

Time:12-21

I have this array:

<?php
$tab= ['10', '11', '12', '12','14'];

I would like to add "4a" to all this values

how I can do that?

CodePudding user response:

You can add value to array like this.

$tab[] = "4a";

or array_push($tab, "4a");

CodePudding user response:

You can make a new array ($tab2) and loop through the previous array ($tab) and add the piece of text ($value) per value.

<?php

$tab = ['10', '11', '12', '12','14'];
$tab2 = [];

$value = '4a';

for ($i = 0; $i < count($tab); $i  ) {
    array_push($tab2, $tab[$i] . $value);
}

The output will look like this:

$tab2 = ['104a', '114a', '124a', '124a', '144a'];

It is also possible to change the existing array. It has the same output.

<?php

$tab = ['10', '11', '12', '12','14'];

$value = '4a';

for ($i = 0; $i < count($tab); $i  ) {
    $tab[$i] = $tab[$i] . $value;
}
  • Related