foreach () Error - php

I'm getting the following warning when running this script:
Warning: Invalid argument supplied for foreach()
This is the script:
$values = array();
foreach ($_POST['rights'] as $right_id)
{
$values[] = '(' . $id . ', ' . $right_id . ')';
}
$_POST['rights']/$id are integers. In this case it was $_POST['rights'] = 1,2,3,4,5; $id = 2.
The strange part is that on a different page with the same kind of input it gives no errors.
The question: What is wrong with it?

check $_POST['rights']
var_dump($_POST['rights']);
I think $_POST['rights'] is not an array.

foreach must take an array, you're passing it an integer. You can't iterate over an integer.
A wise move might be to check whatever you're about to iterate over is indeed an array:
if(is_array($_POST['rights'])){
foreach($_POST['rights'] as $value){
//Whatever you want to do with each $value
}
}
else {
//Let the user know it's hit the fan…
throw new Exception('Help, I\'m not an array :(')
}
PHP docs for arrays: http://php.net/manual/en/language.types.array.php
PHP docs for foreach: http://php.net/manual/en/control-structures.foreach.php

As per your statement $_POST['rights'] is not an array.
It is probably a simple string having 1,2,3,4
You need to convert it into an array with explode function.
e.g
$_POST['rights'] = explode(",", $_POST['rights']);
Then your for loop will work.

The passed array $_POST['rights'] probably is empty.
EDIT:
Like Mark Baker said an empty array is fine. You should go with the other answers.

Related

foreach $key variable clarification

I have this code
if (isset($_POST['submit2']))
{
foreach ($_POST['check_list'] as $key) {
$input = implode(",", $key);
}
} /*end is isset $_POST['submit2'] */
echo $input;
it produces the error " implode(): Invalid arguments passed " when I change the implode arguments to implode(",", $_POST['check_list']) it works as intended.
Can someone clarify why? As far as I understand the $key variable should be the same as the $_POST['submit2'] isn't that what the as in the foreach does?
Sorry if it's a silly question, I'm self taught and sometimes details like that are hard to find online.
You seem confused at several levels, so let me clarify some of them:
You said 'As far as I understand the $key variable should be the same as the $_POST['submit2'] isn't that what the as in the foreach does?'. The answers are NO and NO:
The $key variable outside the foreach loop will contain the last element of the array that's stored in $_POST['check_list'], $_POST['submit2'] seems to be only used to check if is set and nothing else in your piece of code. What foreach does is to traverse any iterator variable (an array in your case) and set the current item in a variable ($key) in your case. So after the loop, $key will contain the last element of that array. For more information refer to the docs: [http://php.net/manual/en/control-structures.foreach.php]
implode expects the second parameter to be an array, it seems you're not providing an array, but any other type. Is the last item of $_POST['check_list'] actually an array?
If you're trying to 'glue' together all items of $_POST['check_list'], you don't need to iterate, you just use implode on that one: $input = implode(",", $_POST['check_list']);. Otherwise, i'm not sure what are you trying to do.
Maybe if you explain what are you trying to do, we can help better.
Foreach already iterates trough your values. You can either get the value and echo it from there or you can add it to another array input if thats what you need:
if (isset($_POST['submit2']))
{
foreach ($_POST['check_list'] as $key => $value) {
$input[] = 'Value #'. $key .' is ' . $value;
}
}
echo implode(",", $input);
You are saying that $_POST['check_list'] is an array if implode() works on it, so no need to loop to get individual items. To implode() the values:
echo implode(',', $_POST['check_list']);
To implode() the keys:
echo implode(',', array_keys($_POST['check_list']));
foreach() iterates over an array to expose each item and get the individual values and optionally keys one at a time:
foreach($_POST['check_list'] as $key => $val) {
echo "$key = $value<br />";
}
implode function needs array as second argument. You are passing string value as second argument. That's why it's not working.

PHP arrays. inserting "$key" => "$value" pair into array with array_push();

Why won't this work?
$slidetotal=1;
$slideids = array();
while ($rowcs = mysql_fetch_array($orig_slides_result)) {
$key = $slidetotal;
array_push($slideids[$key], $rowcs['id']);
$slidetotal++;
}
I get this error:
[phpBB Debug] PHP Notice: in file ///*.php on line 161: array_push() [function.array-push]: First argument should be an array
Although someone has commented you can do this on this page:
http://php.net/manual/en/function.array-push.php , (find: "to insert a "$key" => "$value" pair into an array")
What is the next best way to insert a list of single values into a php array? By the way, I really can't believe it's hard to find something on this with google.com. Seriously?
That PHP.net comment is incorrect. That is pushing $rowcs['id'] onto the array $slideids[$key], not the array $slideids.
You should be doing the following, in place of your array_push() call:
$slideids[$key] = $rowcs['id'];
Why don't you do;
$slidetotal=1;
$slideids = array();
while ($rowcs = mysql_fetch_array($orig_slides_result)) {
$slideids[$slidetotal] = $rowcs['id'];
$slidetotal++;
}
Also you can do like below if you don't need the key to start from 1;
$slideids = array();
while ($rowcs = mysql_fetch_array($orig_slides_result)) {
$slideids[] = $rowcs['id'];
}
ummm hard-searching will work for google I think :)
anyway, error tells you everything you need to know. that means first argument of array_push is not an array, you give a single value (string) to array_push ($slideids[$key]).
Also why do you need to use array_push in php? I'd rather use
$slideids[] = $rowcs['id'];
and what you're trying to do is:
$slideids[$key] = $rowcs['id'];
i guess...

array_unshift() with empty array

I want to add an element to the beginning of an array, but this array might be empty sometimes. I've tried using array_unshift() but it doesn't seem to like empty arrays... should I simply check for the empty array and append the element manually, or does array_unshift() not mind empty arrays but I'm just being a klutz?
Here is my code at the moment:
$sids = array();
$sids = explode(",", $sid['sids']);
array_unshift($sids, session_id());
The contents of the $sids array are taken from a database and are comma separated values.
Thanks,
James
EDIT
I've managed to fix this now - sorry everyone!
Here's the updated code:
$sids = array();
if(!empty($row['sids']))
{
$sids = explode(",", $row['sids']);
}
array_unshift($sids, session_id());
If $sid['sids'] is empty, explode will return FALSE
Then $sids will be equal to FALSE
and the subsequent call to array_unshift will fail.
You should probably make sure $sids is an array before calling array_unshift.
Here's a way to do it:
if(!empty($sid['sids']))
$sids = explode(",", $sid['sids']);
else
$sids = array();
array_unshift($sids, session_id());
First off, your first line of code is pointless; explode always returns a value, whether it be an array or FALSE. You're guaranteed to overwrite that value once you call explode.
Secondly, your code should work. One minor edit I'd make is this:
<?php
$sids = array();
$sids = explode(",", $sid['sids']);
if(is_array($sids))
array_unshift($sids, session_id());
?>
Because (even though your code says otherwise, and that the PHP documentation says otherwise), explode may not always return an array.
Another piece of information that may be useful is whether or not there was any error being reported, and, if so, what the error was.
Best of luck!
array_unshift() accepts the array parameter by reference. This means it must actually be a variable, not an expression like array(). It also means it will modify the variable you pass, not return a new array with the element added. Here's an example to illustrate this:
$array = array();
array_unshift($array, 42);
var_dump($array); // Array now has one element, 42
$sids = explode(",", $sid['sids']);
if (!is_array($sids)) {
$sids = array();
}
array_unshift($sids, session_id());

PHP, problem with str_replace while reading from array

i am new to php, and i am trying to do a script that reads an CSV file(file1.csv) and compare the words in the file with words in a html file (file2.html), if word in file2.html match with the key part in file1.csv it should change the file2.html contents with the value of the key matched ..
what i have done so far is this :
$glossArray = array();
$file_handle = fopen("file1.csv", "r");
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 10000,';');
$glossArray[$line_of_text[0]] = $line_of_text[1];
$counter++;
}
fclose($file_handle);
$file = file_get_contents("file2.html");
foreach($glossArray as $key => $value){
$results = str_replace($key," means ".$value ,$file);
}
echo $results;
i think that my problem occurs when i try to iterate and change values .. because what i see is only the contents of file2.html unchanged
any help would be appreciated
thank you in advance
Nader
P.s. i edited the old code with the new one after your valuable advise .. now it's like this .. but still doesnt work.
Update: changing the foreach with :
$results = str_replace(array_keys($glossArray), "means ".array_values($glossArray), $file);
solved the problem .. but another one comes up: now every time it replaces a string it adds the word 'Array' ahead of it.
You're passing the entire $glossArray in to str_replace each time. You're also passing the initial file contents in each time you do str_replace, so at most you'd see one replacement. I think you want to change to something like this:
$results = $file;
foreach($glossArray as $index=>$value)
{
$results = str_replace($index,$value ,$results);
}
Since str_replace allows arrays for the first two parameters (as another user mentions) you could also do something like this instead of a loop:
$results = str_replace(array_keys($glossArray), array_values($glossArray), $file);
Yes, the problem is in your second foreach. It should read like this:
foreach($glossArray as $key => $value){
$results = str_replace($key,$value ,$file);
}
You forgot the key, so it's replacing every instance of every value in $glossArray with the $value. Good luck with that!
Why are you opening file2.html for reading and writing, then grabbing the contents of it?
(BTW - this is going to go horribly wrong on a system with strict locking)
foreach($glossArray as $value)
{
$results = str_replace($glossArray,$value ,$file);
I think this should be
foreach($glossArray as $old=>$new)
{
$results = str_replace($old, $new, $file);
Although it would be a lot more efficient to load the pairs from the glossary into 2 seperate numbered arrays, then just call str_replace once.
Your first parameter for str_replace should not be $glossArray as that's an array and not the string to replace.
I assume that your CSV-file contains something like "SEARCH;REPLACE"? In that case, your foreach should look like this: foreach ($glossArray as $searchString => $value).
Then try
$file = str_replace($searchString, $value ,$file);
instead of
$results = str_replace($searchString, $value ,$file);
because right now you're overwriting $results again and again with every str_replace ... echo $file when you're done.
BTW: What's $counter doing?
The solution to your new problem (which should really be it's own question, not an edit of the existing one) is that array_values returns an array, and when you concatenate an array with a string, php inserts 'Array' instead of the value.
$results = str_replace(array_keys($glossArray), "means ".array_values($glossArray), $file);
is incorrect. You should do this instead:
$vals = array_values($glossArray);
foreach($vals as $k=>$v)$vals[$k] = 'means '.$v;
$results = str_replace(array_keys($glossArray), $vals, $file);
Notice that the values of glossArray are extracted, and each value concatenated with your string - if you just try and concatenate the string with the array, you'll get a string, not an aray.

Make 1d Array from 1st member of each value in 2d Array | PHP

How can you do this? My code seen here doesn't work
for($i=0;i<count($cond);$i++){
$cond[$i] = $cond[$i][0];
}
It can be as simple as this:
$array = array_map('reset', $array);
There could be problems if the source array isn't numerically index. Try this instead:
$destinationArray = array();
for ($sourceArray as $key=>$value) {
$destinationArray[] = $value[0]; //you may want to use a different index than '0'
}
// Make sure you have your first array initialised here!
$array2 = array();
foreach ($array AS $item)
{
$array2[] = $item[0];
}
Assuming you want to have the same variable name afterwards, you can re-assign the new array back to the old one.
$array = $array2;
unset($array2); // Not needed, but helps with keeping memory down
Also, you might be able to, dependant on what is in the array, do something like.
$array = array_merge(array_values($array));
As previously stated, your code will not work properly in various situation.
Try to initialize your array with this values:
$cond = array(5=>array('4','3'),9=>array('3','4'));
A solution, to me better readable also is the following code:
//explain what to do to every single line of the 2d array
function reduceRowToFirstItem($x) { return $x[0]; }
// apply the trasnformation to the array
$a=array_map('reduceRowTofirstItem',$cond);
You can read the reference for array map for a thorough explanation.
You can opt also for a slight variation using array_walk (it operate on the array "in place"). Note that the function doesn't return a value and that his parameter is passed by reference.
function reduceToFirstItem(&$x) { $x=$x[0]; }
array_walk($cond, 'reduceToFirstItem');
That should work. Why does it not work? what error message do you get?
This is the code I would use:
$inArr;//This is the 2D array
$outArr = array();
for($i=0;$i<count($inArr);$i++){
$outArr[$i] = $inArr[$i][0];
}

Categories