Page 1 of 1

array_fill help

Posted: Mon Aug 25, 2008 1:49 am
by glennnz
Hi

I'm using this code:

Code: Select all

 
<?php
    $row = 1;
    $no_purchased = $_POST['no_purchased'];
    while($row <= $no_purchased)
        {
        $serial = "serial".$row;
        $strings = array_fill(1, $no_purchased, $serial);
        $row++;
        }
    foreach ($strings as $testcase)
        {
        if (ctype_digit($testcase))
            {
            $valid = "Yes";
            }
        else 
            {
            $valid = "No";
            }
        }
    if ($valid == "No")
        {
        print_r ($strings);
        }
    else
        {
        print_r ($strings);
        }
?>
 
The array it generates is:

[1] => serial2
[2] => serial2

This is wrong. I want it to generate:

[1] => serial1
[2] => serial2
[3] => serial3
.......

Why doesn't it work??

Help...

Thanks

Re: array_fill help

Posted: Mon Aug 25, 2008 2:06 am
by Ziq
Why are u use array_fill()? Read documentation http://php.net/

Replace 8 line code:

Code: Select all

 
    $strings[] = $serial;
 

Re: array_fill help

Posted: Mon Aug 25, 2008 2:13 am
by glennnz
Cool, it works with this:

Code: Select all

$strings[] = $_POST['serial'.$row];
but the array starts at [0], how can I get it to start at [1]?

Thanks

Re: array_fill help

Posted: Mon Aug 25, 2008 2:19 am
by Ziq
It's really simple task

Code: Select all

 
    $strings[$row] = $serial;
 
Learn PHP! :)

Re: array_fill help

Posted: Mon Aug 25, 2008 2:23 am
by glennnz
Great, thanks heaps!!

Now I need to get this part working:

Code: Select all

    foreach ($strings as $testcase)
        {
        if (ctype_alnum($testcase))
            {
            $valid = "Yes";
            }
        else 
            {
            $valid = "No";
            }
        }
 
I want it to loop through, and as soon as $valid = "No", exit the loop and keep $valid = "No"

At the moment it loops through the entire array, and $valid ends up as being for the last entry in the array.

G

Re: array_fill help

Posted: Mon Aug 25, 2008 2:31 am
by Ziq
If I have correctly understood

Code: Select all

   
foreach ($strings as $testcase)
        {
        if (ctype_alnum($testcase))
            {
            $valid = "Yes";
            }
        else 
            {
            $valid = "No";
            break;
            }
        }
 
or

Code: Select all

 
$valid = "Yes";  
foreach ($strings as $testcase)
        {
        if (!ctype_alnum($testcase))
            {
            $valid = "No";
            break;
            }
        }
 
Look at continue; and break; in PHP

Re: array_fill help

Posted: Mon Aug 25, 2008 2:44 am
by glennnz
Brilliant!!

Thanks heaps! :D

Glenn