Sorry guys, not being lazy, I know others have had the same error message solved but I still couldn't figure it out so I had to ask.
I have 2 2d arrays each with a string and a corresponding int.
I'm trying to compare the strings in the first array to the strings in the second and if they are the same, i want to add the corresponding integers together.
I am getting the error - "Cannot use a scalar value as an array" on the 7th line
for($countOne=0; $countOne<10; $countOne++)
{
for($countTwo=0; $countTwo<10; $countTwo++)
{
if($blekko_Array['url'][$countOne]==$bing_Array['url'][$countTwo])
{
$blekko_Array['score']['$countOne'] = $blekko_Array['score']['$countOne'] + $bing_Array['score']['$countTwo'];
}
}
}
Anyone know what the problem is?
Thanks
This should do it:
foreach ($blekko_Array as &$blekko) {
foreach ($bing_Array as $bing) {
if($blekko['url']==$bing['url']) {
$blekko['score'] += $bing['score'];
}
}
}
For one thing, your code is hardwired to look through 10 items, so if your array has less than 10 entries, you'll get errors on the missing ones.
Related
I have 2 arrays and i want to make a 3rd array after comparison of the 2 arrays. Code is as follows:
foreach($allrsltntcatg as $alltests)
{
foreach($alltests as $test)
{
foreach($allCatgs as $catg)
{
if($catg['testcategoryid'] == $test['testcategory_testcategoryid'])
{
$catcounts[$catg['testcategoryname']] +=1;
}
}
}
}
It, although returns the right answer, it also generates a PHP error and says undefined index and prints all errors and also the right answer.
I just want to avoid the array out of bound error. Kindly help me
Problem is in if condition correct like below : You have to initialize array first and than you can increment value
if($catg['testcategoryid'] == $test['testcategory_testcategoryid'])
{
if (isset($catcounts[$catg['testcategoryname']]))
$catcounts[$catg['testcategoryname']] +=1;
else
$catcounts[$catg['testcategoryname']] =1;
}
When the array try to add some arithmetic operation of undefined index such as $catg['testcategoryname'] in the $catcounts array then the warning generates. Before add the number you have to check the index is present or not, and of not then just assign value otherwise add into it.
So do it in this way just if condition-
if(....){
if(array_key_exists($catg['testcategoryname'], $catcounts))
$catcounts[$catg['testcategoryname']] +=1; // Add into it
else
$catcounts[$catg['testcategoryname']] = 1; // Assign only
}
More about array key exists--See more
$catg['testcategoryname'] should represent an index in $catcounts array.
So i'm having trouble getting a bit of code to work. Essentially what I want to do is:
in a foreach loop, if a given array value is set, compare that existing value to the current loop value, then set the existing value = current value (for the iteration) if the existing value is already greater than current val. Here is the code i'm working with:
if ($usedebayxml->ack == 'Success') {
foreach($usedebayxml->searchResult->item as $key => $value) {
if(isset($newarray[1]['TotalCost'])) {
if($newarray[1]['TotalCost'] > ((integer)$value->shippingInfo->shippingServiceCost + (integer)$value->sellingStatus->currentPrice)) {
$newarray[1]['Title'] = (string)$value->title ;
$newarray[1]['ShippingCost'] = (integer)$value->shippingInfo->shippingServiceCost;
$newarray[1]['Price'] = (integer)$value->sellingStatus->currentPrice;
$newarray[1]['Condition'] = 'New';
$newarray[1]['TotalCost'] = (integer)$value->shippingInfo->shippingServiceCost + (integer)$value->sellingStatus->currentPrice;
}
}
else
$newarray[1]['Title'] = (string)$value->title;
$newarray[1]['ShippingCost'] = (integer)$value->shippingInfo->shippingServiceCost;
$newarray[1]['Price'] = (integer)$value->sellingStatus->currentPrice;
$newarray[1]['Condition'] = 'Used';
$newarray[1]['TotalCost'] = (integer)$value->shippingInfo->shippingServiceCost + (integer)$value->sellingStatus->currentPrice;
}
}
With this code, what is returned is ultimately the values in the LAST key object in the xml file (im using simpleXML if that helps). In other words, i don't think the first if block (if isset) is being entered into, and the values are being set to whatever the values are for the current iteration. Can anyone see any flaw in my logic here? I've been stumped on this one for a while.
I am a supreme idiot. The logic here is fine, i was just missing a { for the opening else block. dur! After adding this, this bit of code works as intended :)
I'm surprised though that i wasn't throwing any errors without having this....I think that was probably throwing me off in determining why it wasn't working originally.
I have the follow code, but, i get an error in my code.
I cant find the problem but, I think it comes from:
UserManagement::findByUsername($username);
$a_allSections = UserManagement::findByUsername($username);
if($a_allSections)
{
foreach($a_allSections as $a_section)
{
echo $a_section['name'];?>
}
}
else
{
echo 'There's nothing found.' . "\n";
}
Evidently $a_allSections is not an array, so foreach complains. Use var_dump($a_allSections) to find out what exactly it is, and fix your code accordingly.
Check this way
UserManagement::findByUsername($username);
1.the function findByUsername($username) should return some values
2.the class should be included in current document.
3.Check whether your return result as array. if array means check is_array();
4.if above 3 ok in your question then you will not get the error.
$a_allSections may be empty
change condition to
if(is_array($a_allSections)){
...
}
to prevent such error on empty arrays
This question already has answers here:
Remove item from array if it exists in a 'disallowed words' array
(2 answers)
Closed 4 months ago.
I have two arrays: $all_languages and $taken_languages. One contains all languages (like 200 or something), but second - languages that have been chosen before (from 0 to 200).
I need to remove all languages that have been taken ($taken_languages) from $all_languages and return new array - $available_languages.
My solution was two loops, but, first, it doesn't work as expected, second - it's 'not cool' and I believe that there are better solutions! Can you point me to the correct path?
This is what I have done before, but, as I said, it doesn't work as expected...
if (!empty($taken_languages)) {
foreach ($all_languages as $language) {
foreach ($taken_languages as $taken_language) {
if ($taken_language != $language) {
$available_languages[] = $language;
break;
}
}
}
} else {
$available_languages = $all_languages;
}
Thanks in advice!
PHP has a built in function for this (and just about everything else :P)
$available_languages = array_diff($all_languages, $taken_languages);
PHP Manual (array_diff)
The array_diff function will work for you.
http://php.net/manual/en/function.array-diff.php
This question already has answers here:
Invalid argument supplied for foreach()
(20 answers)
Closed 7 years ago.
Not a major problem but I was wondering if there is a cleaner way to do this. It would be good to avoid nesting my code with an unnecessary if statement. If $items is empty php throws an error.
$items = array('a','b','c');
if(!empty($items)) { // <-Remove this if statement
foreach($items as $item) {
print $item;
}
}
I could probably just use the '#' error suppressor, but that would be a bit hacky.
There are a million ways to do this.
The first one would be to go ahead and run the array through foreach anyway, assuming you do have an array.
In other cases this is what you might need:
foreach ((array) $items as $item) {
print $item;
}
Note: to all the people complaining about typecast, please note that the OP asked cleanest way to skip a foreach if array is empty (emphasis is mine). A value of true, false, numbers or strings is not considered empty.
In addition, this would work with objects implementing \Traversable, whereas is_array wouldn't work.
The best way is to initialize every bloody variable before use.
It will not only solve this silly "problem" but also save you a ton of real headaches.
So, introducing $items as $items = array(); is what you really wanted.
$items = array('a','b','c');
if(is_array($items)) {
foreach($items as $item) {
print $item;
}
}
If variable you need could be boolean false - eg. when no records are returned from database or array - when records are returned, you can do following:
foreach (($result ? $result : array()) as $item)
echo $item;
Approach with cast((Array)$result) produces an array of count 1 when variable is boolean false which isn't what you probably want.
I wouldn't recommend suppressing the warning output. I would, however, recommend using is_array instead of !empty. If $items happens to be a nonzero scalar, then the foreach will still error out if you use !empty.
I think the best approach here is to plan your code so that $items is always an array. The easiest solution is to initialize it at the top of your code with $items=array(). This way it will represent empty array even if you don't assign any value to it.
All other solutions are quite dirty hacks to me.
foreach((array)$items as $item) {}
i've got the following function in my "standard library"
/// Convert argument to an array.
function a($a = null) {
if(is_null($a))
return array();
if(is_array($a))
return $a;
if(is_object($a))
return (array) $a;
return $_ = func_get_args();
}
Basically, this does nothing with arrays/objects and convert other types to arrays. This is extremely handy to use with foreach statements and array functions
foreach(a($whatever) as $item)....
$foo = array_map(a($array_or_string)....
etc
Ternary logic gets it down to one line with no errors. This solves the issue of improperly cast variables and undefined variables.
foreach (is_array($Items) || is_object($Items) ? $Items : array() as $Item) {
It is a bit of a pain to write, but is the safest way to handle it.
You can check whether $items is actually an array and whether it contains any items:
if(is_array($items) && count($items) > 0)
{
foreach($items as $item) { }
}
Best practice is to define variable as an array at the very top of your code.
foreach((array)$myArr as $oneItem) { .. }
will also work but you will duplicate this (array) conversion everytime you need to loop through the array.
since it's important not to duplicate even a word of your code, you do better to define it as an empty array at top.