Behavior of array_search() - php

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!

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.

Array is not clearing properly?

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.

How do I delete array elements one by one every time I reload the page?

<?php
session_start();
$_SESSION['del']=array("a1","a2","a3","a4","a5");
unset($_SESSION['del'][0]);
echo implode(" ",$_SESSION['del'])
?>
How do I remove each array element one by one every time I refresh the page?
here is the code
<?php
session_start();
if(isset($_SESSION['del'])) { // to make sure array is not set again as in question
unset($_SESSION['del'][0]); // remove the first element
$_SESSION['del'] = array_values($_SESSION['del']); // to shift rest of the elements one location left for making indexes starts from 0
} else { // set session array only once
$_SESSION['del']=array("a1","a2","a3","a4","a5");
}
echo implode(" ",$_SESSION['del']); // print results
?>
if(isset($_SESSION['del']))
{
if(is_array($_SESSION['del']))
{
array_shift($_SESSION['del']);
}
}
Code Explanation
if the session del is currently set.
and that the session['del'] is an array
remove the first value of the array del.
I am not sure if it works with $_SESSION, but if it is an array then array_shift() would be what you are looking for:
array_shift($_SESSION['del']);

For-Each Loop Misses First Index When Multiple Indices Exist

I've got the below PHP which works great when the array of locations only have 1 value, but when it has any number more than 1, the information on the first location keeps printing out blank. The array is set by calling explode on a comma-delimited list. When I set the array manually immediately before the loop, it works great! Yet not when I use explode, even though I printed the array and can confirm it's getting set up just as I expect (with the correct 0 index). The code I have is:
echo "<ul>";
foreach ($locations as &$value)
{
$locationDetails = mysql_query("SELECT id, name FROM locations WHERE id='$value'");
$locationDetailRow = mysql_fetch_assoc($locationDetails);
echo "<li>".$locationDetailRow['name']."</li>";
}
unset($value);
echo "</ul>";
I've confirmed that the query does not fail, that $value is what I expect it to be, and that the name does exist for the first $value in every case.
Any reason this should be failing on the first case when there are multiple locations?

Iterate through session array?

I haven't use PHP for some time, and I need some help to create some lines of code. I wrote this line of code some years ago for a website
array_push($_SESSION['buildingsAlreadySeenList'],$id);
This is my problem, I just want to iterate through the array and put the first value at index 0 to $buildingId and then next time put the value of index 1 to $buildingId with som While loop i guess? I know it's easy, but sadly I haven't used PHP for some time! Preciate the help! Thanks!
Use foreach()
foreach($_SESSION['buildingsAlreadySeenList'] as $id => $value) {
echo $id; // this is the index and for the first time this is like to give o if the indexes were not manipulated somehow
//put the index value to buildingid
$buildingId = $id;
echo $value; //the actual value of the array
}
Update
To check if the array is empty count the variables
if(count($_SESSION['buildingsAlreadySeenList'])) {
//array is not empty
} else {
//array is empty
}

Categories