0

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?

4 Answers 4

4

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.

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

Comments

1

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

Comments

0

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

Comments

0

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

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.