0

I have an counter, that gives me the number of times I found a phrase in a document. And Now I need to create a variable for each, example:

//Counter
$fstNameCtr = 0;
do {    
    $fstNameCtr = $fstNameCtr + 1;
} while ($firstNameRange->Execute($objFstName));
echo '$fstNameCtr';

The result came back with 2 instances of the phrase and I'm looking for, now I would like to create a variable for each dynamically based on the number in the counter as following like as:

$instance1 
$instance2 

or

$instanceOne
$instanceTwo

Any help would be appreciated, thank you.

2 Answers 2

1

This would usually be a list, use:

$x=array();

Then:

$x[]=$newThing; //"append"

You can print it using print_r, and as it is a "list"

$i = 0;
while($i != count($x)) {
    echo($i.": ".$x[$i]);
    $i++;
} 

Note I have used this instead of a for loop DELIBERATELY. PHP doesn't distinguish between lists and dictionaries, instead you have this horrible dictionary of numeric indices! So if you remove say the 1st thing (so $x[1]), you have a list with entries at 0, 2, 3,.....

I use this to show that I am treating the array as a list, I use for when I want the key-value pairs (or just the values)

BE CAREFUL WHEN POPPING from such a list, because then certain indices wont exist.

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

Comments

0

It sounds like you want to have a range of counters, each representing a "topic" or certain measurement. Here's a simple implementation, using a dictionary, which might be useful for you:

function increment(&$counters, $key) {
    if (array_key_exists($key, $counters)) {
        $counters[$key]++;
    } else {
        $counters[$key] = 1;
    }
}

This can then be used with an array of counters like this:

$counters = array();
$phrase = "foo bar foo";
foreach (explode(" ", $phrase) as $word) {
    increment($counters, $word);
}
print_r($counters);

The above code will output:

Array
(
    [foo] => 2
    [bar] => 1
)

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.