I have a following function in php:
function addEntryHere($day, $numberId, $numberOfTexts, $entries) {
foreach($entries as $entry) {
if($entry->$day == $day) {
$entry->addToEntry($numberId, $numberOfTexts);
}
}
$newEntry = new Entry($day);
$newEntry->addToEntry($standId, $numberOfTexts);
array_push($entries, $newEntry);
//print_r($entries);
}
and when I invoke this function in a loop:
while($row = mysqli_fetch_array($result)) {
echo "count table before: " . count($entries);
for($i=23; $i<26; $i++) {
addEntryHere($i, $row[1], $row[2], $entries);
//print_r($entries);
}
echo "count table after: " . count($entries);
}
I see only:
count table before: 0
count table after: 0
My addToEntry
method is quite simple:
function addToEntry($numberId, $numberOfTexts) {
switch($numberId) {
case 1: $this->number1+= $numberOfTexts; break;
case 2: $this->number2+= $numberOfTexts; break;
}
}
So why do I get constantly the output 0, even though there is some data in the $result
? I've decided to pass the array $entries
to the addEntryHere
method because I couldn't refer to it in the method, even though I thought it has a global scope...
======= EDIT
after following the watcher's suggestion I modified my code, but then this line:
if($entry->$day == $day) {
throws me the error:
Notice: Undefined property: Entry::$23
and the browser prints such errors many, many times (since it's in the while loop). What might be the problem here?
You are only modifying the local variable inside the function. After every invocation of the function, that local variable disappears and is lost. What you want to do is return the value of your computation back to the calling context so that it can be used later:
array_push($entries, $newEntry);
return $entries;
}
And the call:
while($row = mysqli_fetch_array($result)) {
echo "count table before: " . count($entries);
for($i=23; $i<26; $i++) {
$entries = addEntryHere($i, $row[1], $row[2], $entries);
//print_r($entries);
}
echo "count table after: " . count($entries);
}
If you're trying to work with the global scope, note that in PHP you have to explicitly import the global scope inside of the function:
function addEntryHere($day, $numberId, $numberOfTexts) {
global $entries;
But realize that, in general, working with global variables is an anti-pattern and is advised against.