0

Is there a way to automatically create numbers?

For example if I knew how many numbers I wanted I could do this

for($i = 0; $i == 10; $i++)
{
    $i++;
}

but for the code I have at the moment I'm not sure how to do that.

Here is my code


$products = [
    'prodcut_1' => [
        'name' => 'Product 1',
    ],
    'prodcut_2' => [
        'name' => 'Product 2',
    ],
    'prodcut_3' => [
        'name' => 'Product 3',
    ]
];

$arr = [];
foreach($products as $key => $prodcut)
{
    $arr[$key] = [
        'number' => // the item number will go here
        'name' => $item['name'],
        'unit' => 'unit_'.$key,
        'rate' => 'rate_'.$key
    ];
}

3 Answers3

1

You can create a new variable that could hold the actual number and increment it on each loop. For example of your code you can create the variable and name it $itemNumber, with initial value of 1:

$itemNumber = 1;
foreach($products as $key => $item)
{
    $arr[$key] = [
        'number' => $itemNumber,
        'name' => $item['name'],
        'unit' => 'unit_'.$key,
        'rate' => 'rate_'.$key
    ];
    $itemNumber++;
}

P.S: I noticed some code mistakes in the foreach loop, you have the product variable which is not used, but instead it's item

AnTrakS
  • 733
  • 4
  • 18
0

You can use same $i++ in foreach like this:

$arr = [];
$i = 0; //don't forget to set $i to zero
foreach($products as $key => $product)
{
    $arr[$key] = [
        'number' => $i++,
        'name' => $product['name'],//$product not item ;)
        'unit' => 'unit_'.$key,
        'rate' => 'rate_'.$key
    ];
}

read about for loop, what his do

https://www.php.net/manual/en/control-structures.for.php

$i = 0; $i == 10; $i++

first you put 0 to $i

$i == 10; this is a statement that you are waiting for. More safely to use "Less than or equal to" $i <= 10;. is a good practice

then you write expression for every loop $i++;

do same at foreach and good luck ;)

  • That way of example of the code will trigger parse error, because of the ; at the end of the line with key `number`. Also the counter will start from 0, not from 1, he could probably use pre-increment instead of post-increment – AnTrakS Mar 01 '21 at 06:56
0

Just use the key value for that like

...$key+1;

once key always start in zero at loop

Prospero
  • 2,190
  • 2
  • 4
  • 18