Problem in reading from Array in 'foreach'

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Shamma009
Forum Newbie
Posts: 2
Joined: Fri Apr 09, 2010 5:22 pm

Problem in reading from Array in 'foreach'

Post by Shamma009 »

What exactly where you trying to do here?

Code: Select all

		array ($finaltot[$j] = $row);
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Problem in reading from Array in 'foreach'

Post by requinix »

Whoops, looks like someone deleted a post.

Code: Select all

$final =  $value* $totElectrici;
$value is an array. You can't multiply an array by a number.

Code: Select all

$finaltot[$j] = $row
That bit needs to be slightly different.
Shamma009
Forum Newbie
Posts: 2
Joined: Fri Apr 09, 2010 5:22 pm

Re: Problem in reading from Array in 'foreach'

Post by Shamma009 »

how can I get the value out of the array ?
minorDemocritus
Forum Commoner
Posts: 96
Joined: Thu Apr 01, 2010 7:28 pm
Location: Chicagoland, IL, USA

Re: Problem in reading from Array in 'foreach'

Post by minorDemocritus »

Shamma009 wrote:how can I get the value out of the array ?
2 ways. If the array is keyed by names, you can reference by the key name or key index:

Code: Select all

$userInfo = array('name' => 'john', 'birthday' => '1985-08-23', 'town' => 'jacksonville');
$name = $userInfo['name'];
$birthday = $userInfo['birthday'];
// $name and $birthday will be the same if you do it this way:
$name = $userInfo[0];
$birthday = $userInfo[1];
If the array is keyed by integers, you have to reference by the key index:

Code: Select all

$errorMessages = array('Invalid username or password', 'Email address is not valid', 'Your session has expired, please log in again.');
$firstError = $errorMessages[0];
$secondError = $errorMessages[1];
foreach ($errorMessage as $error) {
    echo 'The error received was: ' . $error;
}
More, very helpful information is available here... I STRONG RECOMMEND reading the whole thing, since there are a few gotchas to be careful of with arrays: http://php.net/manual/en/language.types.array.php.
Post Reply