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
    ];
}
2
  • By using count function, you can get the number of elements in array. On that basis you can loop through array. Commented Mar 1, 2021 at 6:45
  • check here,stackoverflow.com/questions/11048173/… Commented Mar 1, 2021 at 6:51

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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 ;)

1 Comment

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
0

Just use the key value for that like

...$key+1;

once key always start in zero at loop

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.