In an array that is chunked into blocks of 11 values, I need to know if a particular one has a TRUE value. If only one is TRUE, that's all I need and the foreach can stop after it sets a value. All I could think of to do was to make it set a SESSION value to TRUE if a match but that does not stop the loop from continuing and then I had the issue of the SESSION giving false results unless it was then unset which I did after the value was set. Seems rather an indirect way to do it so any suggestions?
$FormValues = array_chunk($Fields, $NoValues); // Group together the field values
// Check if form uses multiple selection fields and add appropriate form tags
foreach ($FormValues as $multi) :
if (isset($multi[9]) === TRUE) $_SESSION['useMulti'] = TRUE;
endforeach;
$enableMulti = (isset($_SESSION['useMulti'])) ? " enctype=\"multipart/form-data\"" : "";
unset($_SESSION['useMulti']);
Here is an example of an array and, in this case, none should return TRUE:
$Fields = array("First Name","Title",$Title,1,0,30,"","","","","",
"Quote","Quote",$Quote,4,0,30,"","",$quoteSQL,FALSE,$siteDB,
"Location","Location",$Location,1,0,30,"","","","","",
"Date","EventDate",$EventDate,41,0,15,"",TRUE,"","","",
"Time","Time",$Time,39,0,0,"","",$sqlTime,"","",
);
You can simply iterate over the original array in strides of 11, rather than using array_chunk.
To make the loop stop iterating once you've found what you want, use break.
You don't need a session variable for this, they're only for preserving values between different PHP scripts. You don't really even need another variable, you can just set the enableMulti variable in the loop.
$enableMulti = "";
for ($i = 9; i < count($Fields); $i += $NoValues) {
if ($Fields[$i] === true) {
$enableMulti = " enctype=\"multipart/form-data\"";
break;
}
}
If you really want to use foreach you do need to use array_chunk, and you can also use array_column.
$enableMulti = "";
$chunks = array_chunk($Fields, $NoValues);
foreach (array_column($chunks, 9) as $value) {
if ($value === true) {
$enableMulti = " enctype=\"multipart/form-data\"";
break;
}
}
You can also get rid of the loop entirely:
if array_search(TRUE, array_column($chunks, 9)) {
$enableMulti = " enctype=\"multipart/form-data\"";
} else {
$enableMulti = "";
}
I get a website as a cURL response, and I pass it to this function. Then I itterate through the string, doing some processing. It works, but I get this error:
Notice: Uninitialized string offset: 75817 in
/var/www/html/wp-content/plugins/crg-daily/lib/CragslistRawDumpProcessor.class.php
on line 7
Here is the code:
public function rollSausage($dump){
$anchorArray = array();
$dumpLength = strlen($dump);
$skipToLetter = 1;
while($skipToLetter < $dumpLength){
$skipToLetter++;
$letter = $dump[$skipToLetter];
...
}
}
Any ideas? I think it has something to do with the type of string being submitted. It is a raw cUrl response. I'm scraping a web page.
Increment your $skipToLetter after you use it (preferably at the end of the while loop). And you might also start at 0, not 1
$skipToLetter = 0;
while($skipToLetter < $dumpLength){
$letter = $dump[$skipToLetter];
...
$skipToLetter++;
}
}
Here's the reason: assume you have a string with length of 4. This means that the last index in the string is 3. Your index goes up to 3. It gets compared in the while loop (3<4)? and the answer is true. The code enters the while loop and increments the value of the index which will be greater than the last index of the string, thus causing the warning.
Updated your code...
public function rollSausage($dump){
$anchorArray = array();
$dumpLength = strlen($dump);
$skipToLetter = 1;
while($skipToLetter < $dumpLength){
$skipToLetter++;
if( siset( $dump[$skipToLetter]) )
$letter = $dump[$skipToLetter];
...
}
}
}
I am struggling with the undefined notice comes and sometimes not. I am not sure why I am having this error.
foreach($_POST['toplevel_menus'] as $toplevel_menu){
$toplevel_extracted = explode("|", $toplevel_menu);
$submenu_id = $toplevel_extracted[5];
if(isset($_POST[$submenu_id]) && !empty($_POST[$submenu_id])){
foreach($_POST[$submenu_id] as $submenu){
$extracted = explode("|" $submenu);
$submenu_name = (isset($_POST[$subname][$extracted[1]]))
? trim($_POST[$subname][$extracted[1]])
: "";
}
}
}
The line number 7 is
$submenu_name = (isset($_POST[$subname][$extracted[1]])) ? trim($_POST[$subname][$extracted[1]]) : "";
The best practice to always access arrays via index is to check them with isset first. This way you can make sure to avoid such errors.
I have a function userNumber($number) where I want to return two variables. I know it's not possible to return more than one variable in PHP functions, so I created an array so I can access any index/value from the array when needed. The function tests if the user's input is between 100 & 200, and should output the cube and square root of the number.
I want to call the function in variables:
$calculationSquare = userNumber($number);
$calculationCube = userNumer($number);
But I do not see how I can access each value of the array in each variable(like the formatting of calling an index - array[]);
Here is the function that converts the number into square/cube and returns the value via array:
function userNumber($number) {
$square = "";
$cubed = "";
if(100 < $number && $number < 200) {
$sqaure = sqrt($number);
$cubed = $number * $number * $number;
return array($square, $cubed);
} // end if
else {
return false;
} // end else
} // end function userNumber
Again, here are the two variables that I'd like to populate with the return values (but don't know how to access he square or cube in the array to populate the variables accordingly):
$calculationSquare = userNumber($number);
$calculationCube = userNumber($number);
Any input on how to access the individual array values in the function would be appreciated, or resources on learning more about this.
In your current implementation you can do this in PHP >= 5.4.0:
$calculationSquare = userNumber($number)[0];
$calculationCube = userNumber($number)[1];
Or better, this would only call the function once:
$result = userNumber($number);
$calculationSquare = $result[0];
$calculationCube = $result[1];
Or maybe even better, use list() to assign array values to individual variables:
list($calculationSquare, $calculationCube) = userNumber($number);
The above approaches would also work with the following returned array, but it may be more descriptive:
return array('square' => $square, 'cube' => $cubed);
You can then use list() or:
$calculationSquare = $result['square'];
$calculationCube = $result['cube'];
I have a script which includes a double-quoted string (used to make an html table, if it makes a difference) that incorporates about a dozen variables. Each of those variables is modified by a while loop. I would like to push each set of values to a multidimensional array on each iteration of the loop. Right now I could do
array_push($my_array, $var1, $var2, $var3, ...);
but that is awkward.
Is there a way to just dump all the variables in this string into my array, something like:
array_push($my_array, get_vars_from_string($string));?
(Obviously it would have been wonderful if the variables used in the script were in an array to begin with, but I didn't write the original and changing that would require too many changes to the structure of the program.)
By "variables inside a string" I mean: $table = "<td>$var1</td><td>$var2</td><funky stuff with subheadings> stuff..."
function get_vars_from_string($param)
{
$arrfromstring=explode('$',$param);//or tokenize here
$ret=array();//return value
//then do the formatting and get the names of the variables,this can be done by some other functions too
foreach($arrayfromstring as $key)
array_push($ret,${$key});//this is the part you are looking for.
}
You will understand what i mean by the the tokenizing part I think. The interesting part is the ${$key}. An example.
To get variables from string, you can use token_get_all(), but you have to use string not processed by php, but raw line of code that assigns this string to variable.
Proof of concept code with bad practices:
<?php
$string_vars = array();
$double_quote_started = false;
$all_vars = array();
$table = "";
$var1 = 5;
$var2 = -5;
while($var1-- && $var2++) {
// note single quotes, this does not evaluate variables but treats everything as string
$table_str = <<<'EOT'
$table .= "<td>$var1</td><td>$var2</td><td>funky stuff</td>";
EOT;
//evaluate the line as it was earlier
eval($table_str);
// since this is is first iteration, let's search our string for them
if (empty($string_vars)) {
foreach(token_get_all("<?php " . $table_str) as $token) {
if (is_array($token) && $token[0] == T_VARIABLE && $double_quote_started) {
$string_vars[] = substr($token[1],1);
} elseif ($token === '"') {
$double_quote_started = !$double_quote_started;
}
}
}
$this_iteration = array();
foreach($string_vars as $var){
// variable variable to get content of variable
$this_iteration[$var] = $$var;
}
// save this iteration vars
$all_vars[] = $this_iteration;
}