cgwebprojects
cgwebprojects

Reputation: 3482

Generating a random string php?

I am trying to generate a random bit of html via php, I can't get it to work?

$i = 96;
$minder = '';
while($i >= 0) {
    // 1
    if (rand(0, 1) == 0) {
        $minder . '<li class="0 1" title="1"></li>';
    // 2
    } else {
        $minder . '<li class="0 2" title="2"></li>';
    }
    --$i;
}
echo $minder;

How do I get the li to append to the string minder? I should end up with a list of 96 li?

Upvotes: 0

Views: 208

Answers (4)

Ben D
Ben D

Reputation: 14489

Syntax should be:

$minder .= '<li class="0 2" title="2"></li>';

Note the .=

Concatenating two strings is done with a . (i.e. $string = "first part"." second part";) but if you want to concatenate a string to an existing variable, you can do it the long way:

$existing_string = $existing_string." some more text";

or use the shorthand syntax, which is much simple:

$existing_string .=" some more text";

Also... your class names! Using a numeric digit as a class name is going to give you headaches down the road. Technically you can do it, but it requires vigilance and you may just want to avoid it by calling your class 'class_1' and 'class_2', etc. From w3c:

In CSS1, a class name could start with a digit (".55ft"), unless it was a dimension (".55in"). In CSS2, such classes are parsed as unknown dimensions (to allow for future additions of new units). To make ".55ft" a valid class, CSS2 requires the first digit to be escaped (".\35 5ft")

Given how easy it is to just avoid this, I'd follow Triptych's rule on this:

A name [should] begin with an underscore (_), a dash (-), or a letter(a–z), followed by any number of dashes, underscores, letters, or numbers. There is a catch: if the first character is a dash, the second character must2 be a letter or underscore, and the name must be at least 2 characters long.

Upvotes: 4

Vigrond
Vigrond

Reputation: 8198

You are not assigning $minder to anything. The concatenation operator "." does not do assignments.

Try this instead

$minder .= '<li class="0 2" title="2"></li>';

Upvotes: 0

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 175088

Use the append/assign operator .=

$minder .= '<li class="0 1" title="1"></li>';

Also, a more efficient way of doing what you need:

while($i >= 0) {
        $rand = mt_rand(1,2);
        $minder . '<li class="0 $rand" title="2"></li>';
    }
    --$i;
}

Upvotes: 1

Borealid
Borealid

Reputation: 98559

I think you meant $minder .=, not $minder ..

Upvotes: 0

Related Questions