Why does PHP tell me this variable isn't defined? - php

I'm trying to filter some logs like I need them and tried to it dynamic. I have some domains and I'm trying to filter some things from it, and it all works like I want it - but now I changed the domain name and now my code doesn't work anymore. It says one variable isn't defined.
$sp_bots = shell_exec("grep bot | awk '{print $12}' /var/www/laravel/logs/vhosts/domain.log");
$array_sp_bots = explode("\n", $sp_bots);
$all_bots = array();
foreach($array_sp_bots as $bots){
if(strpos($bots, "bot")){
$all_bots[] = $bots;
}
}
# count values of strings in array
if (!empty( $all_bots )) {
$bots = array_count_values($all_bots);
arsort($bots);
$mostOccuring = max(array_count_values($all_bots));
$bot_keys = array_keys($bots);
#number of total bots
$count_bots = count($all_bots);
}
and in my returns:
return view('/domains/data', [
'count_bots' => $count_bots,
'bot_keys' => $bot_keys,
'mostOccuring' => $mostOccuring,
]);
but all three variables in my return are undefined.. anybody knows why?

You have to initialize the array as an empty array before the loop:
$all_bots = array(); //init the empty array
foreach($array_sp_bots as $bots)
{
if(strpos($bots, "bot"))
{
$all_bots[] = $bots; //here you can add elements to the array
}
}
in your case, if the loop does not execute at least one time, the variable $all_bots will be undefined
EDIT
After the loop, to handle the case when the array is empty do somthing like this:
//if there is some element in all_bots...
if ( ! empty( $all_bots ) )
{
# count values of strings in array
$bots = array_count_values($all_bots);
arsort($bots);
$mostOccuring = max(array_count_values($all_bots));
$bot_keys = array_keys($bots);
#number of total bots
$count_bots = count($all_bots);
}
//handle the case the variable all_bots is empty
else
{
$bots = 0;
$count_bots = 0;
$bot_keys = 0;
$mostOccuring = 0;
}
EDIT2
You have the variables undefined in your return because when all $all_bots is empty they are not set. Check my edit above, i have added them to the if statement. But you have to handle this case in your application according to your needs, think this way: What these variables should contain when $all_bots is empty? Then assign the values to the variables in the if statement

It is happening because after changing the domain it is not executing inside the loop. Try with -
$all_bots= array(); // Define an empty array
foreach($array_sp_bots as $bots){
if(strpos($bots, "bot")){
$all_bots[] = $bots;
}
}
# count values of strings in array
$bots = array_count_values($all_bots);
If the $array_sp_bots is empty then it would not execute the loop & $all_bots would not be defined. For that case the count would be 0.
Or may might want to add some check for that -
if(empty($all_bots)) {
// Some error message
} else {
# count values of strings in array
$bots = array_count_values($all_bots);
arsort($bots);
$mostOccuring = max(array_count_values($all_bots));
$bot_keys = array_keys($bots);
#number of total bots
$count_bots = count($all_bots);
}

Related

Looking for an element in an array in PHP

I don't know if I'm managing this array in the best way.
The array I have is this:
$bass = $_POST['bass'];
$selected_scale = $_POST['scale'];
$major_scales = array
(
array("C","D","E","F","G","A","B","C","D","E","F","G","A","B",),
array("C#","D#","E#","F#","G#","A#","B#","C#","D#","E#","F#","G#","A#","B#",),
array("Db","Eb","F","Gb","Ab","Bb","C","Db","Eb","F","Gb","Ab","Bb","C",),
array("D","E","F#","G","A","B","C#","D","E","F#","G","A","B","C#"),
array("D#","E#","F##","G#","A#","B#","C##","D#","E#","F##","G#","A#","B#","C##"),
array("Eb","F","G","Ab","Bb","C","D","Eb","F","G","Ab","Bb","C","D"),
array("E","F#","G#","A","B","C#","D#","E","F#","G#","A","B","C#","D#"),
array("E#","F##","G##","A#","B#","C##","D##","E#","F##","G##","A#","B#","C##","D##"),
array("Fb","Gb","Ab","Bbb","Cb","Db","Eb","Fb","Gb","Ab","Bbb","Cb","Db","Eb"),
array("F","G","A","Bb","C","D","E","F","G","A","Bb","C","D","E"),
array("F#","G#","A#","B","C#","D#","E#","F#","G#","A#","B","C#","D#","E#"),
array("Gb","Ab","Bb","Cb","Db","Eb","F","Gb","Ab","Bb","Cb","Db","Eb","F"),
array("G","A","B","C","D","E","F#","G","A","B","C","D","E","F#"),
array("G#","A#","B#","C#","D#","E#","F##","G#","A#","B#","C#","D#","E#","F##"),
array("Ab","Bb","C","Db","Eb","F","G","Ab","Bb","C","Db","Eb","F","G"),
array("A","B","C#","D","E","F#","G#","A","B","C#","D","E","F#","G#"),
array("A#","B#","C##","D#","E#","F##","G##","A#","B#","C##","D#","E#","F##","G##"),
array("Bb","C","D","Eb","F","G","A","Bb","C","D","Eb","F","G","A"),
array("B","C#","D#","E","F#","G#","A#","B","C#","D#","E","F#","G#","A#"),
array("B#","C##","D##","E#","F##","G##","A##","B#","C##","D##","E#","F##","G##","A##"),
array("Cb","Db","Eb","Fb","Gb","Ab","Bb","Cb","Db","Eb","Fb","Gb","Ab","Bb")
);
$bass is a string, like the one inside the arrays. The $selected_scale is just a number.
What I'm trying to do is to find the $bass in one of those array in the position of $selected_scale. Basically, $bass = $major_scales[$selected_scale]. Therefore I want to create a loop in order to get the elements after that.
But I don't know how to manage in this case the situation. I've looked everything in internet and try various solutions without success. I'd like to know how can I do it. Thanks
Try to use next loop:
// if value exists in mentioned index
if (in_array($bass,$major_scales[$selected_scale])){
// index of that value in that array
$tmp_ind = array_search($bass,$major_scales[$selected_scale]);
// length of the array
$len = count($major_scales[$selected_scale]);
// store values after this value
$res = [];
for ($i=$tmp_ind;$i<$len;$i++){
$res[$i] = $major_scales[$selected_scale][$i];
}
}
print_r($res);
Demo1
If you need to find value by index $selected_scale in one of these arrays and also store values after this position:
foreach($major_scales as $ar){
if ($ar[$selected_scale] == $bass){
// length of the array
$len = count($ar);
// store values after this value
$res = [];
for ($i=$selected_scale;$i<$len;$i++){
$res[$i] = $ar[$i];
}
}
}
print_r($res);
Demo2

Unset array element and reseting array values in PHP

So I have 2 files. In file 1 I have a table and there I randomly select some fields and store (store in session) them in an array of 2D arrays. When I click on the cell I send this data to my file 2 where I want to check if I clicked on a randomly selected array or not and if I did, I want to remove this 2D array from an main array.
But as soon as I click on one of the selected arrays, the array crashes.
File 1 PHP stuff immportant for this:
session_start();
$_SESSION['arrays'] = $stack ;
File 2 PHP:
session_start();
if (isset($_SESSION['arrays'])) {
$stack = $_SESSION['arrays'];
for ($i = 0; $i< count($stack);$i++){
if($cooridnates == $stack[$i]){
unset($stack[$i]);
array_values($stack);
$i--;
$Result = true;
break;
}
}
$_SESSION['arrays'] = $stack ;
I am suspecting the error might be in 2 things:
count($stack) used, but I don't believe this is the main reason.
The way I store session.
I have tried using manuals from W3Schools and official PHP website and also SOF, but with no use.
But still, I am not sure if the array_values() and unset() is working correctly since the thing chrashes and I can't test it correctly.
I would appreciate any tips.
You need to assign the result of array_values($stack); back to the $stack variable.
$stack = array_values($stack);
There's also no need to use $i-- when you do this, since you're breaking out of the loop after you find a match.
Instead of a loop, you can use array_search():
$pos = array_search($coordinates, $stack);
if ($pos !=== false) {
unset $stack[$pos];
$Result = true;
$stack = array_values($stack);
$_SESSION['arrays'] = $stack;
}
you can do this like that by using foreach loop:
session_start();
if (!empty($_SESSION['arrays'])) {
foreach( $_SESSION['arrays'] as $key => $val){
if($cooridnates == $val){
unset($_SESSION['arrays'][$key]); // if you want this removed value then assign it a variable before unsetting the array
$Result = true;
break;
}
}
}

Removing a certain number out of a session array in PHP

I have a button next to all my 'shop items' that can remove one of the shop item, however i need it to just remove one, and not rid the entire array of the number, i thought this was possible by using a break statement when i found the number i want to remove, but it removes all of the numbers.
if (isset($_GET['remove']) && isset($_SESSION['shopitems'])) {
if (in_array($_GET['remove'], $_SESSION['shopitems'])) {
for ($i = 0; $i < sizeof($_SESSION['shopitems']); $i++) {
if ($_SESSION['shopitems'][$i] == $_GET['remove']) {
$shopArray = $_SESSION['shopitems'];
if(sizeof($shopArray) == 1) {
$_SESSION['shopitems'] = null;
$_SESSION['added'] = null;
} else {
array_splice($shopArray, $i, $i);
$_SESSION['shopitems'] = $shopArray;
}
break;
}
}
}
}
Here i check if the URL contains the remove variable and the session is set, once i have done this, i check if the array contains the number that is put in the URL, if so i'll start a for loop and check if the key index of the session shop items is equal to the URL variable, if so i want to remove it, however if i use array_splice, suddenly they are all gone, is this because of the function i am using? Or is the break not executing correctly?
Why don't you try array_search() and unset()? It's easier, have a look at the code below and adapt it to your situation:
$array = [1, 5, 6, 12];
$wantToRemove = 5;
$key = array_search($wantToRemove, $array);
unset($array[$key]);
var_dump($array);
You can format your $_SESSION['shopitems'] like this :
$_SESSION['shopitems'] = array (
"item_id" => "item_info",
"item2_id" => "item2_info",
...
)
and do unset($_SESSION['shopitems'][$_GET['remove']]).
Your code could be :
if (isset($_GET['remove']) && isset($_SESSION['shopitems']))
if (isset($_SESSION['shopitems'][$_GET['remove']]))
unset($_SESSION['shopitems'][$_GET['remove']])

Incrementing an array's value is causing warnings in the log

I am trying to create an array that holds the count of each course we offer based on location and then instructor. Here is sample code
$courseCnt = array();
foreach($courseList as $course){
$courseCnt[$course['location']][$course['instructor']] += 1
}
This code creates the array properly and displays well but I get a bunch of warnings like:
Unidentified index "Orlando" for locations, Unidentified index "John
Smith" for instructor
I have found that if I just make it = 1 instead of += 1 the warnings go away but of course this makes every course for location/instructor 1 which is not good.
My next though was checking if it exists, if it doesn't, make it 1 and if it does += 1. Here is an example
if(isset($courseCnt[$course['location']][$course['instructor']]){
$courseCnt[$course['location']][$course['instructor']] += 1
}else{
$courseCnt[$course['location']][$course['instructor']] = 1
}
This results in the fatal error:
Cannot use string offset as an array
$course array structure is just a 2 dimensional array pulled from sql
Sample:
courseID location instructor
1 Orlando John Smith
2 Detroit Bill Murray
You are not checking if the location exists before checking for the instructor in your first line of the new version of the code. You need to check if it exists and create it in your $courseCnt array if it doesn't (as an empty array). After that, you can check for the instructor:
// Initialise the empty array
$courseCnt = array();
// Create location if not in array
if( ! isset($courseCnt[$course['location']])) {
$courseCnt[$course['location']] = array();
}
// Either increment the instructor or create with initial value of 1
if ( isset($courseCnt[$course['location']][$courseCnt[$course['instructor']]]) ) {
$courseCnt[$course['location']][$courseCnt[$course['instructor']]] += 1;
}
else
{
$courseCnt[$course['location']][$courseCnt[$course['instructor']]] = 1;
}
You've got a lot of square brackets going on in there, so you might find it easier to read if you use PHP's array_key_exists (documentation) instead of isset:
// Initialise the empty array
$courseCnt = array();
// Create location if not in array
if( ! array_key_exists($course['location'], $courseCnt)) {
$courseCnt[$course['location']] = array();
}
// Either increment the instructor or create with initial value of 1
if ( array_key_exists($course['instructor'], $courseCnt[$course['location']]) ) {
$courseCnt[$course['location']][$courseCnt[$course['instructor']]] += 1;
}
else
{
$courseCnt[$course['location']][$courseCnt[$course['instructor']]] = 1;
}

array_replace() / array_merge() | ( $_SESSION = array() ) argument is not an array?

I have this code for my school project and thought the code does its job on what i wanted it to do, i still keep on getting the error about $_SESSION[] is not an array argument when using the array_replace() and array_merge() functions:
Session is already initiated on the header:
// Start Session
session_start();
For initialising the $_SESSION['cart'] as an array:
// Parent array of all items, initialized if not already...
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = array();
}
For adding products from a dropdown menu: - (Just to see how the session is assigned:)
if (isset($_POST['new_item'])) { // If user submitted a product
$name = $_POST['products']; // product value is set to $name
// Validate adding products:
if ($name == 'Select a product') { // Check if default - No product selected
$order_error = '<div class="center"><label class="error">Please select a product</label></div>';
} elseif (in_array_find($name, $_SESSION['cart']) == true) { // Check if product is already in cart:
$order_error = '<div class="center"><label class="error">This item has already been added!</label></div>';
} else {
// Put values into session:
// Default quantity = 1:
$_SESSION['cart'][$name] = array('quantity' => 1);
}
}
Then here is where the issue comes, when they try to update the product:
// for updating product quantity:
if(isset($_POST['update'])) {
// identify which product to update:
$to_update = $_POST['hidden'];
// check if product array exist:
if (in_array_find($to_update, $_SESSION['cart'])) {
// Replace/Update the values:
// ['cart'] is the session name
// ['$to_update'] is the name of the product
// [0] represesents quantity
$base = $_SESSION['cart'][$to_update]['quantity'] ;
$replacement = $_SESSION['cart'][$to_update] = array('quantity' => $_POST['option']);
array_replace($base, $replacement);
// Alternatively use array merge for php < 5.3
// array_merge($replacement, $base);
}
}
Note that both the functions array_replace() and array_merge() are updating the values and doing what the initial goal was, but the problem is that i still keep on getting that one argument($base) is not an array issue.
Warning: array_replace() [function.array-replace]: Argument #1 is not an array in ...
any suggestions for a better way to approach this issue would be a valuable help :)
Thanks for your help :)
Edit: The in_array_find() is a function that i use in replacement of in_array() as it doesn't apply to finding values in a multi-dimensional array: specifically 2 depth arrays:
found it from here and it works for me
The code for it is:
// Function for searching values inside a multi array:
function in_array_find($needle, $haystack, $strict = false) {
foreach ($haystack as $item => $arr) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}
return false;
}
array_replace returns the replaced array. So you need to do:
$base=array_replace($base, $replacement);
Also, I suggest using named keys consistently throughout, as opposed to mixing named and numeric:
$base = $_SESSION['cart'][$to_update]['quantity'];
EDIT:
This may not be exactly what you're going for...
I set up a test situation without using $_SESSION, and I got the same error you did. I changed the code as follows and no longer get the error.
$sesh=array(
'cart'=>array(
0=>array(
'quantity'=>1
)
)
);
$to_update=0;
$new_quantity=5;
//$base = $sesh['cart'][$to_update]['quantity']; <--- changed this to line below
$base = $sesh['cart'][$to_update];
$replacement = $sesh['cart'][$to_update] = array('quantity' => $new_quantity);
$base=array_replace($base, $replacement);
echo"<pre>";print_r($base);echo"</pre>";
PHP FIDDLE: http://phpfiddle.org/main/code/mvr-shr
This have solved this issue:
Basically as per the structure: (Lets slice it into bits)
$_SESSION['cart'] = array();
then
$_SESSION['cart'][$name] = array('quantity' => 1);
finally:
$base = $_SESSION['cart'][$to_update]['quantity'] ;
$replacement = $_SESSION['cart'][$to_update] = array('quantity' => $_POST['option']);
array_replace($base, $replacement);
The reason why it says that the argument $base is not an array is because:
['quantity'] in $base is not an array as it forms the 'quantity' => 1 what we need is the array() value from the array('quantity' => 1); for it to be identified as an array.
So final answer should be: $base = $_SESSION['cart'][$to_update];
as there is only one array() recorded in where the $to_update resides so the replacement argument shall replace this identified array.
$_SESSION only exists when a Session starts. In order to do that you need to add on top of all your code session_start() otherwise the session will not start, unless you define it on php directives.

Categories