Array is not clearing properly? - php

I have a form that allows a user to add and delete objects from an array. The deleting process works by taking the array and dumping all the contents into a dropdown list the user can select what they want to delete from.
<?php
session_start(1);
if (isset($_SESSION['array'])){
$narray = $_SESSION['array'];
if ($narray != NULL){
echo "DDDD";
}
echo 'Select an object to delete: ';
echo '<select name=deleteob>';
foreach($narray as $drop){
echo'<option value="'.$drop.'">'.$drop.'</option>';
}
echo '</select>';
Whenever all of the contents are deleted, the array does not 'clear'? I'm not sure the word, it does not seem to be actually emptying. The echo 'DDDD' is to see if the array has something contained inside of it. I've also tried seeing if the array is NULL, but neither will echo anything, but the dropdown list is still being created with an empty selection. The array is being pulled from a process page by a session variable on another page. Basically array has nothing inside of it but acts like it does. Anything i am doing wrong to cause this? Sorry for bad english

Change
if ($narray != NULL) {
to:
if (!empty($narray)) {
If you delete all the elements of an array, it's still an array, and is not equal to null.

Related

Array index increment

I have this array in php code. I want to have that whenever page is being called it should print value of first array index and when next time second value of array index and so on... what modification I could do? for now it´s printing everything when being called single time.
<html>
<?php
$addresses = array('ifcbxespra', 'ifcheqjbmea', 'ifcqiknsa', 'ifcqirtjla', 'ifcwqsrlmn', 'ifclmkmzhz','ifcwdujhgc','ifcihddngh','icffhzudcd','ifchnsqzgs','ifcgssqrhg');
foreach ($addresses as &$value) {
echo $value ;
}
?>
</html>
I'm not sure if I understood what you want. But if you want to print the first array's value when the page loads one time, the second array's value when the page loads another time and so on, you can do this:
<?php
if(!isset($addresses) || empty($addresses)){ //checks if the array is not initialized or if it's empty
$addresses = array('ifcbxespra', 'ifcheqjbmea', 'ifcqiknsa', 'ifcqirtjla', 'ifcwqsrlmn', 'ifclmkmzhz','ifcwdujhgc','ifcihddngh','icffhzudcd','ifchnsqzgs','ifcgssqrhg');
echo $addresses[0]; //print the first value
array_splice($addresses, 0, 1); //removes the first element of the array and reindexes it
}else{
echo $addresses[0]; //print the first value
array_splice($addresses, 0, 1); //removes the first element of the array and reindexes it
}
The logic behinds it is: if the array already exists and is not empty (it has values), print the first value and then remove it, so next time the first value will be the second actual value. When the array is empty, redefine it as to start again.
You can search for more information on array_splice() here.
P.S.: you have to use PHP's $_SESSION to save the array between the pages.
You can use something like $_SESSION and store there the last index.
For example:
$array = array('one', 'two', 'three');
if (!$_SESSION['nextIndex'] || $_SESSION['nextIndex'] >= count($array)) {
$_SESSION['nextIndex'] = 0
}
// print the value
echo $array[$_SESSION['nextIndex']];
// increment the nextIndex
$_SESSION['nextIndex']++;
NOTE: This will only work for the same user. Each page reload will increment the array index. But if you need some cross-user counting, then you have to store the information somewhere on the server, like a DB or even a simple txt file.
Check out this example: http://hibbard.eu/how-to-make-a-simple-visitor-counter-using-php/
Finally I solved this problem with the MySQL. created a column with all code. and then call the script every-time when user press button. In the script first I fetch first raw and print that value, and then, delete that raw. so every-time user will get unique value from the list of code And it is working fine.

Behavior of array_search()

I am using function array_search to unset elements from a session array. Problems: if the key found is 0, returns false; if is selected the last element from the "list", it doesn't take it off from the browser's page but it is deleted from the array (works fine with the other elements); if i print out the $key it doesn't show the right key, but a value that keeps growing every time the result is a key that has been already "used".
The first and second problems are of most interest to me. The code that unsets elements from array seem correct and logic to me so i need help again...
So I've set up a pagination that retrieves data from a DB table. Everything prints fine.
while($row=mysqli_fetch_assoc($query))
{
echo "<tr><td>".$row['ID']."</td><td>".$row['name']."</td><td>";
if($row['stoc']==0) echo "Stoc 0</td></tr>";
else echo "Add this</td></tr>";
}
Then if isset(GET['item']) ("Add this" button), build a session array and add to it the items selected one by one:
if(isset($_GET['item']))
{
$cod=$_GET['item'];
$item_q=mysqli_query($conn, "SELECT name FROM mousi WHERE cod='$cod'");
$item_f=mysqli_fetch_assoc($item_q);
if(!in_array($item_f['name'],$_SESSION['prod'])) $_SESSION['prod'][]=$item_f['name'];
foreach($_SESSION['produse'] as $elm)
echo $elm."<a href='mousi.php?item=$cod&del=$elm'>Delete</a><br />";
}
And finally there is an if isset(GET['del']) condition writen before if isset(GET[item]) and this GET[del] unsets an element from the array $_SESSION['prod']:
if(isset($_GET['del']))
{
$key=array_search($_GET['del'], $_SESSION['prod']);
if($key!==false)
{
unset($_SESSION['prod'][$key]);
echo $key." 'selected' key<br />"; //why would this grow like the last result is stored?
print_r(array_values($_SESSION['prod'])); //just to see if the elements are actually deleted and they are, except the first one (key=0)
}
else echo "Key not found";
}
Thank you in advance!

Adding a key to a foreach created array not adding all values

foreach($_POST['door_check'] as $door_check)
{
$_SESSION['front_door']['door'] = $door_check;
}
I have this little section of code that checks how many boxes were checked and then creates an array of the check box values.
The thing is, when I add that 'door' key, the array only adds one value no matter how many checkboxes were checked. When I just leave it empty, it adds all of them like [0], [1], [2] etc
Why is this?,
Your foreach() loops overwrites old variable each time. You need to make your session variable an array, for example
foreach($_POST['door_check'] as $door_check)
{
$_SESSION['front_door']['door'][] = $door_check;
}
edit: Don't forget to validate that data when you save it for later use.
Try something like this:
foreach($_POST['door_check'] as $door_check) {
$_SESSION['front_door']['door'][] = $door_check;
}
or maybe even:
$_SESSION['front_door']['door'] = $_POST['door_check'];

Object Loop Not Working as Expected

I will be honest, I have just started learning objects and I am stuck.
I want to loop through an array of objects and display the name and description for each. But either nothing is displayed or it displays all the names first and then all the descriptions.
I am pulling the information from an API into the object:
// get tasks
foreach($tasksList->items as $task_details) {
$tasks_name[$task_details->id]=$task_details->name;
$tasks_desc[$task_details->id]=$task_details->description;
$tasks_details[$task_details->id]=$task_details->id;
$tasks_progress[$task_details->id]=$task_details->progress;
}
foreach($tasks_name as $taskid=>$my_task_name) {
echo "Task_Name: " . $my_task_name . "</br>";
$task_id = $task_details->id;
foreach($tasks_desc as $taskid1=>$my_task_desc) {
if($taskid==$task_details->id) {
echo "Task_Desc: " . $my_task_desc . "</br>";
}
}
}
Now what I don't understand is: inside the first foreach loop it is like a while loop while i=0, it checks $tasks_name[0], then $tasks_name[1] and so on.
However, I am not sure how to figure out what the id is in the current loop it is on, so I can tell it to only print the description of the current loop and not display all of them.
To be honest I am copying this from another example, but I don't quite understand it. I plan to study objects more, but this is holding me up on my current code:
foreach($tasks_desc as $taskid1=>$my_task_desc)
I understand it is looping through all the $tasks_desc and assigning the value to $my_task_desc but what is the signifigance of $taskid?
Sorry for the newbie questions. :)
This is poorly written. I would move on to another tutorial if it's a tutorial. Either that or the line that task_id is used was left out.
Anyway, tasks_name is an array of tasks indexed by the ID. So the outer loop in the second block loops over the keys/values of that array (the ID is the key, taskid. It was assigned by $task_details->id in the first loop above).
The second loop goes over all of the tasks again, but this time by description task_desc instead of by name. It's trying to find the task_desc with an ID that matches the ID of the task_name before (which would make it the same task).
That's unnecessary, though, because you could just store all of the entries (name, desc, etc.) in one array indexed by the ID instead of storing each in their own array:
(this is the first loop):
foreach($tasksList->items as $task_details) {
$all_tasks[$task_details->id]['name'] = $task_details->name;
$all_tasks[$task_details->id]['desc'] =$task_details->description;
// Don't need the ID again; it's the key
$all_tasks[$task_details->id]['progress'] = $task_details->progress;
}
However, you don't even need to do that, because you can just iterate over tasksList->items when you need to.
There's no need for two loops. To display name and description for each object, one loop is enough:
foreach($tasksList->items as $task_details) {
echo 'name: ', htmlspecialchars($task_details->name);
echo ', description: ', htmlspeciachars($task_details->description);
}
(I also don't understand why you want to store every object field in its own array first?)

Show db row with a specific not null column in foreach loop before others are displayed

I have a listings table, and each listing has column called 'top'. Basically, if top is not null, I want that listing to show up first, then the others.
Right now, my code is like this:
foreach ($results as $result):
echo $result->name;
endforeach;
This will show me everything, but I want the rows with 'top' not null to show up first. What's the best way to go about this?
Can't you apply an ORDER BY to the query that feeds $results?
I agree with Aaron... the best thing to do is to order them so that they are first in the query.
If for some reason you couldn't do that you could do a few other things:
Sort the object or array in PHP... may have to use a custom function .. if that's the case see: Sort Object in PHP
Grab the rows that only have the NULL first, print them, then grab the ones that aren't null.
You could loop through the array twice. First only printing the NULLs, then again to print the others.
Try
foreach ($result as $row){
Then specify each element you want in order.
echo $row['top']
echo $row['your next data row']...
and have them space exactly how you want.
And if you need it formated, try using <pre> first.
You can also add a if statment.
$data = $row['top']
if($top == 1) { then echo this } else {echo the values that are null }
Based on your comment below #Aaron Bertrand's answer, you would need an order clause in your sql like:
ORDER BY ISNULL(`top_ad`), the_rest_of_your_order_clause

Categories