n00bie PHP Question

Status
Not open for further replies.

Drover

New member
Nov 28, 2006
369
1
0
Houston, TX
This should be REALLY simple but unfortunately my PHP is for shit so I'm asking for a little help.

What I'm trying to accomplish is essentially just to have two phrases in different places on a site that are tied together so the correct pair of phrases displays together. However, I have about 10 pairs of the phrases that I want to rotate randomly.

For instance, if 'Apple' displays in the first instance I want 'Fruit' to display down the page. If 'Can' is displayed, it should say 'Aluminum' in the second location. But I obviously don't want 'Apple' then 'Aluminum'.

Also, I'm trying to pull the data from a txt file elsewhere on my site.

I've tried a number of ways but as I said my PHP skills suck. I've tried using an associative array but am not figuring out how to pull the index and value separately. I've also tried tying the second phrase to the numerical value PHP assigns the first from an array, then pulling the same numerical item from a second array. It seems either of these would work if I knew how.

A little help, please....

Thanks in advance for any assistance.
 


I can't help with the first part but on one of my sites I read a text file like this..
Code:
 <?php include (TEMPLATEPATH . '/right_text.txt');/?>
And I just have a right_text.txt file in the templates root folder.

edit: after re-reading your post maybe this isn't what you were looking for. Oh well, I'll leave it for future searchers.
 
Alright here's a short and sweet code snippet that'll do what you want:

Code:
$phrases=array("apples"=>"fruit","broccoli"=>"vegetable","php"=>"cool");

function returnRandomPhrase($phrases) {
    $firstWords=array_keys($phrases);
    shuffle($firstWords);
    
    $phrasePair[]=$firstWords[0];
    $phrasePair[]=$phrases[$firstWords[0]];
    
    return $phrasePair;
}

Usage:
$pair=returnRandomPhrase($phrases);

echo "First word is ".$pair[0];
echo "Second (associated) word is ".$pair[1];
 
That looks about like what I need, nogenius. I appreciate it. But I'm still having trouble with it. Can you elaborate a bit on what goes where?

For instance mine looks like this...

Above the </head> I have:

Code:
function returnRandomPhrase($phrases) {
    $firstWords=array_keys($phrases);
    shuffle($firstWords);
    
    $phrasePair[]=$firstWords[0];
    $phrasePair[]=$phrases[$firstWords[0]];
    
    return $phrasePair;
}

$pair=returnRandomPhrase($phrases);

?>
Then in the body of my page, where the key goes, I put in:

Code:
<?php echo .$pair[0]; ?>
And where the value goes I put

Code:
<?php echo .$pair[1]; ?>
But I'm sure I'm doing something wrong since it's not working.
 
Do you have this part in your code?

$phrases=array("apples"=>"fruit","broccoli"=>"vegetable","php"=>"cool");

Also, drop the "." in the echo statements.
 
Do you have this part in your code?

$phrases=array("apples"=>"fruit","broccoli"=>"vegetable","php"=>"cool");

Also, drop the "." in the echo statements.

Yeah, I have that first part. Mine's just a little different because it's pulling the array from a text file. So I have:

Code:
$phrases = array_map("trim", file("phrasematrix.txt"));
I actually got that part to work.
I dropped the "." and it's now just putting a "0" where it should echo a random phrase.
 
Well it looks like my little piece that was pulling from the text file is part of the problem. When I do it that way, it just echoes a "0" or "1" in both places. I'd really like the array to pull from a separate txt file. Anyone know another way to do this?

However, when I do the array nogenius's way, the key (first word) is returned correctly but the associated value isn't returned by:
Code:
<?php echo $pair[1]; ?>
It's just blank where that should be.

Thoughts?
 
I've just got it working no problems, just try pasting this in the body of your text exactly as it is here and let us know what happens:


<?php
$phrases=array("apples"=>"fruit","broccoli"=>"vegetable","php"=>"cool");

function returnRandomPhrase($phrases) {
$firstWords=array_keys($phrases);
shuffle($firstWords);

$phrasePair[]=$firstWords[0];
$phrasePair[]=$phrases[$firstWords[0]];

return $phrasePair;
}

$pair=returnRandomPhrase($phrases);

echo "First word is ".$pair[0];
echo "Second (associated) word is ".$pair[1];

?>
 
Me FTW!

First set up your text file like this:

Code:
Apple
Fruit
Can
Aluminum
Each value should have it's own row. Keep the pairs in consecutive rows.

This script will randomly pick a set to display:

Code:
<?php

    $compare = file('filename.txt');
    
    //the number of rows in the file.
    $num = count($compare);
    
    //randomly generate a pair to display.
    $position = rand(0,$num);
    
    // to test whether $number is odd you could use the arithmetic
    // operator '%' (modulus) like this
    if( $odd = $positionr%2 )
    {
        // $odd == 1.  We need to decrease our $position in the file.
        $second = $compare[$position];
        $position--;
        $first = $compare[$position];
    }
    else
    {
        // $odd == 0.  We are where we need to be in the file.
           $first = $compare[$position];
        $position++;
        $second = $compare[$position];
    }

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-
8859-1" />
<title>Untitled Document</title>
</head>
<body>
I really love the <?php echo $first; ?> because it can be like something totaly different, like a <?php echo $second; ?> !!
</body>
</html>

This code is untested, but should work.
 
Well it looks like my little piece that was pulling from the text file is part of the problem. When I do it that way, it just echoes a "0" or "1" in both places. I'd really like the array to pull from a separate txt file. Anyone know another way to do this?

However, when I do the array nogenius's way, the key (first word) is returned correctly but the associated value isn't returned by:
Code:
<?php echo $pair[1]; ?>
It's just blank where that should be.

Thoughts?

What is the format of your text file?
 
Found an error in my code change the line
if( $odd = $positionr%2 )

to

if( $odd = $position%2 )
 
Why not just something like this....

<?
$randomTerms = array(
array('can', 'aluminum'),
array('mac', 'computer'),
array('something', 'else')
);

$randKey = mt_rand(0, count($randomTerms) - 1);
?>

then, on your page, where you want the terms to show up do...

<? echo $randomTerms[$randKey][0]; ?> (This is the first value: can, mac, somethign)
<? echo $randomTerms[$randKey][1]; ?> (this is the second value: aluminum, computer, else)
 
Why not just something like this....

<?
$randomTerms = array(
array('can', 'aluminum'),
array('mac', 'computer'),
array('something', 'else')
);

$randKey = mt_rand(0, count($randomTerms) - 1);
?>

then, on your page, where you want the terms to show up do...

<? echo $randomTerms[$randKey][0]; ?> (This is the first value: can, mac, somethign)
<? echo $randomTerms[$randKey][1]; ?> (this is the second value: aluminum, computer, else)

That would be great except that in his original problem that he's pulling the data from a text file.
 
@Rage9: Your method would work but the file format wouldn't be ideal. I think it'd be easier to maintain (and less code) if each key/value pair was comma delimited per line. Then you can just load in the contents of the file, explode it to an array by newline character, and then explode each line by comma.

words.txt
Code:
apple,fruit
broccoli,vegetable
php,cool
lorem,ipsum

Code:
<?php
$source = explode("\n", file_get_contents("words.txt"));
$words = array();
for($i = 0; $i < count($source); $i++)
{
 $line = explode(",",$source[$i]);
 $words[] = array($line[0],$line[1]);
}
shuffle($words);
$word = $words[0];
?>
<h1><?php echo $word[0]; ?></h1>
<h2><?php echo $word[1]; ?></h2>
 
@Rage9: Your method would work but the file format wouldn't be ideal. I think it'd be easier to maintain (and less code) if each key/value pair was comma delimited per line. Then you can just load in the contents of the file, explode it to an array by newline character, and then explode each line by comma.

That's an interesting way to do it also, and by all means does work. However you way of doing it is overly inefficient. Although I'm not saying that the code will be but in place with limited resources, but regardless why write such bloated code? It's just bad practice.

Besides, in the original post he talked about only having about 10 sets of these, so I doubt my slightly non-optimal file format can't be used for raw speed.
 
Found an error in my code change the line
if( $odd = $positionr%2 )
to
if( $odd = $position%2 )

This is wrong.

= in php is an assignment operator not a comparison operator like ==, ===, != and !==.

$odd = $position%2 means set the value of $odd to $position%2 which will by default always return a true value in PHP meaning the else statement will never fire.

Also, audax's code is much more efficient and scalable.

Finally, I notice a lot of code on here is "x"=>"z", explode("\n") which is fine but if you really want to optimise for maximum performance use single quotes instead as double quotes in php means the parser should be looking for variables inside the string to replace (which creates extra overhead)
 
Also, audax's code is much more efficient and scalable.

Finally, I notice a lot of code on here is "x"=>"z", explode("\n") which is fine but if you really want to optimise for maximum performance use single quotes instead as double quotes in php means the parser should be looking for variables inside the string to replace (which creates extra overhead)

Thanks.

Good catch on the double quotes. I try to pay attention to using single quotes when I can but I had just switched from writing some C# (only double quotes for strings).
 
This is wrong.

= in php is an assignment operator not a comparison operator like ==, ===, != and !==.

$odd = $position%2 means set the value of $odd to $position%2 which will by default always return a true value in PHP meaning the else statement will never fire.

Also, audax's code is much more efficient and scalable.

Finally, I notice a lot of code on here is "x"=>"z", explode("\n") which is fine but if you really want to optimise for maximum performance use single quotes instead as double quotes in php means the parser should be looking for variables inside the string to replace (which creates extra overhead)

I know all about comparison operators, this was just kind of thrown together last second before having to go to work. I even put at the bottom I didn't test it, so I tend to miss some things. I fixed my code, so *yeah* it works now.

And no, audax's code is not more efficient. Scalable? Maybe, but not more efficient. I prepared both our code, with the exact same text files - but in each of our formats. I also included timing into both our php pages so all you have to do is run them. They both run our algorithms 10,000 times and take the average of all the times. Running them one on one I was ahead. However running them 10,000 times has run me into problems, mine run fine and I have a great time. However his code seems to not like to be run many times in a row, so it would be nice if someone else wanted to test it.

File can be found here: MEGAUPLOAD - The leading online storage and file delivery service

As promised new code!
Code:
<?php
    $compare = file('file.txt');
        
    $num = count($compare);
    $num--;
    
    $position = rand(0,$num);
    
    if( $position%2 != 0 )
    {
        $second = $compare[$position];
        $position--;
        $first = $compare[$position];
    }
    else
    {
        $first = $compare[$position];
        $position++;
        $second = $compare[$position];
    }

?>   
<h1><?php echo $first; ?></h1>
<h2><?php echo $second; ?></h2>
 
Status
Not open for further replies.