PHP array limit? [closed] - php

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
friends i am new in php. I am playing with array. So i am unable to solve one login using array. In this program i want to show array limit. I have number of data it's come form Database. But i want to show limit data like ( 10 posts only ). I know the MYSQL query to show limit data. But i am trying with array. So please help to solve this logic thanks.
here is the code.
$reverse = array_reverse($showpost, true);
foreach ($reverse as $key=>$postvalue) {
$latestpost = explode(',', $postvalue['postcategory']);
if (in_array("3", $latestpost)) {
// result here...
}
}
I have save the category this format (1,2,3,4,5,6). That's why I have used explode() function.
My DataBase fields name are ( post_id, postname, postcategory, postdisc,).

Not sure if I've understood the problem correctly but I think it maybe related to this link
$input = array("a", "b", "c", "d", "e");
$output = array_slice($input, 0, 3); // returns "a", "b", and "c"

You can use array_chunk() function
CODE:
<?php
$reverse = array_reverse($showpost, true);
foreach($reverse as $key=>$postvalue){
$latestpost = explode(',', $postvalue['postcategory']);
$chunks = array_chunk($latestpost, 3);
print_r($chunks);
}
?>

If you're only wanting to show 10 rows, and result here... is where each post is show, then something like this may work:
$postsShown = 0;
$reverse = array_reverse($showpost, true);
foreach ($reverse as $key => $postvalue) {
if ($postsShown >= 10) {
break;
}
$latestpost = explode(',', $postvalue['postcategory']);
if (in_array("3", $latestpost)) {
// result here...
$postsShown++;
}
}
All this does is count how many posts are shown using the $postsShown variable, and increments it when a new post is shown. When this variable reaches 10 (IE, 10 posts are shown), the loop will be terminated using the break command.

maybe you can use a session variable to save few attempts the user used to log, and you validate it in the server.
with this code you can create a session variable:
session_start();
$_SESSION['name_of_my_variable'] = 'value of my session variable';
and for example each time the user tries to log you can increase the value of your counter in the session variable:
the first time you needs create the session variable:
session_start();
$_SESSION['log_counter'] = 1;
and the next attempts you increment the counter like this:
session_start();
$log_counter = $_SESSION['log_counter'];
$log_counter++;
$_SESSION['log_counter'] = $log_counter;
check if the user already reached the limit:
session_start();
if ($_SESSION['log_counter'] == 10)
{
echo "Limit reached";
}
This is the final code:
// init session variables
session_start();
// Check if exist the session variable
if (isset($_SESSION['log_counter']))
{
// Enter here if the session variable exist
// check if the log_counter is equals to the limit
if ($_SESSION['log_counter'] == 10)
{
echo "Limit reached";
}else
{
// increase the counter
$log_counter = $_SESSION['log_counter'];
// this increate 1 more to the log_counter session variable
$log_counter++;
// here we save the new log_counter value
$_SESSION['log_counter'] = $log_counter;
}
}else
{
// Enter here if not exist the session variable
// this create the log_counter session variable
$_SESSION['log_counter'] = 1;
}

Related

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;
}
}
}

simple statistics with PHP

I have a bunch of JSON objects stored in my database with user input,
i.e.
{ "items": [
{question_id: 5, answer_id: 4, is_correct: 1},
{question_id, 45, answer_id: 233, is_correct: 0},
...]
}
and I'd like to build statistics about which answer_id for which question_id is answered most, etc.
I have tried PHP associative arrays like so:
<?php
$stats = array();
foreach($jsonObject->items as $item)
{
$stats[$item->question_id][$item->answer_id]++;
}
?>
I'm using PHP much like I'd use AWK, and it works, but the problem is that I get a lot of warnings like this one
Undefined offset: 23026
Where 23026 is the id of the question or the answer.
How do I debug / ensure the accuracy of the statistics? Is there a better way of doing this?
The notices occurs, because you try to increase a not existing value for the first occurrence of the question or answer id. If you want to run your script without warning you simply have to check if it was already set or not.
Some sample code which should work:
<?php
$stats = array();
foreach ($jsonObject->items as $item) {
if (isset($stats[$item->question_id][$item->answer_id])) {
$stats[$item->question_id][$item->answer_id]++;
} else {
// Set to 1 if not exist
$stats[$item->question_id][$item->answer_id] = 1;
}
}
?>

Load next array item in PHP quiz

I am creating a small PHP quiz and I have a Multidimensional Array set up (which houses my question titles and questions), I then use rand_array to chose one of the arrays and display it into my page. After it has been displayed I use unset($row); to remove it from my Multidimensional Array so that the same question is never shown twice.
There are three buttons (for the three answers) and when that is clicked it will give 0, 10 or 20 points to the user. I have used this to get the points back:
if (isset($_POST["Answer1"])){
$points = $points + 20;
initialQuestions();
}
I run initialQuestions(); again to get the next question but this obviously resets my entire array, how do I make it skip to the next question with the previous item removed from the array eventually leading it to be a blank array?
Any help would be much appreciated.
use array splice instead of unset cause the vallue gets nulled but the key remains
initialQuestions()? And where is Your array?
use initialQuestions($question_array) and return array without current question;
Something like this
$questions = array('your array');
function initialQuestions($questions) {
//get some question
//remove it from array
return $questions;//return this array
}
then
if (isset($_POST["Answer1"])){ $points = $points + 20; $questions = initialQuestions($questions);
or globalize $questions array
function initialQuestions() {
global $questions;
//get some question
//remove it from array
}
But best for me is using $_SESSION to store Your $question array.
you can just randomly pull a question from the all_question array, and save this 'used' question into Session, then doesn't matter what you do in the POST back, the next time when you pull a 'next' question from all_question, you just check it see if it's already stored in the 'used' Session, if so, pull again, if not, you got what you want.
<?php
session_start();
$all_question = array(
//put all your question here...
);
//pull a question out
$new_question = pull_question( $all_question );
//save this question to the 'used' session
$_SESSION['used_question'][] = $new_question;
?>

Cookie not save in foreach

People
I am trying to build a shopping cart, So i will have to pass the id , quantity and location_id to the function. In the function, i will look at the id and location_id passed in, if similar id and location_id is found. I will +1 to the item. However, if i use the function in array, it is not working.
Below is another function i built to test the variables pass to function within foreach.
But is does not say the first variable i passed in. it will only save the latest variable.
Below is my function codes :
static public function test($id , $per_min, $location_id_cart = 0){
echo $new_cart = $id.'-'.$per_min.'-'.$location_id_cart;
if(isset($_COOKIE['cart_item'])){
$last = $_COOKIE['cart_item'];
$testing = $last.','.$new_cart;
}else{
$testing = $new_cart;
}
$set = setcookie("cart_item", $testing, time()+3600);
var_dump($_COOKIE);
}
Below is my codes calling the function :
$id = 125;
$multi_location = array(636 , 789);
$multi_quantity = array();
$multi_quantity[636] = 5;
$multi_quantity[789] = 10;
$array_key = array_keys($multi_quantity);
foreach($array_key as $o){
if(!in_array($o , $multi_location)){
unset($multi_quantity[$o]);
}
}
$count = 0;
foreach($multi_location as $i){
ZCart::test($id , $multi_quantity[$i], $i);
}
My result :
'cart_item' => string '125-10-789' (length=10)
My expected result :
'cart_item' => string '125-5-636,125-10-789'
if i refresh my page, the result i get is this :
'cart_item' => string '125-10-789,125-10-789,125-10-789,125-10-789,125-10-789,125-10-789,125-10-789'
The cookie will only save the latest value given in the array. it does not save 125-5-636 to the cookie.
Why? can anyone help me on this please? Thank you!
try the following code:
static public function test($id , $per_min, $location_id_cart = 0){
$new_cart = $id.'-'.$per_min.'-'.$location_id_cart;
if(isset($_COOKIE['cart_item'])){
$last = $_COOKIE['cart_item'];
$testing = $last.','.$new_cart;
}else{
$testing = $new_cart;
}
$set = setcookie("cart_item", $testing, time()+3600);
//This line deals with adding to the cookie while the script is running
$_COOKIE['cart_item'] = $testing;
//var_dump($_COOKIE);
}
I have a feeling that the $_COOKIE array isn't being updated when you use setcookie(), this is why we update it manually with the line below it.
Also I'd remove the var_dump() call, along with echoing the $new_cart variable, as this will stop setcookie() from working. Instead, I would put it at the bottom of your calling code:
$id = 125;
$multi_location = array(636 , 789);
$multi_quantity = array();
$multi_quantity[636] = 5;
$multi_quantity[789] = 10;
$array_key = array_keys($multi_quantity);
foreach($array_key as $o){
if(!in_array($o , $multi_location)){
unset($multi_quantity[$o]);
}
}
$count = 0;
foreach($multi_location as $i){
ZCart::test($id , $multi_quantity[$i], $i);
}
var_dump($_COOKIE);
If you are implementing a shopping cart, I'd strongly recommend using sessions, which allow you to store the sensitive stuff on the server side away from harm and are in my experience much easier to work with than cookies!
Another option would be to store the user's cart in a database and then if they aren't logged in link to that cart with an ID stored in a cookie. This would allow the cart to stay around if the user closes their browser but keeps the secure stuff from the cookie. I hope this makes sense!
because you are not using array or different variable. Every time you call function in loop, It updates value of cart_item.It doesnot store value in different variables.

How to add visited pages urls into a session array?

Everytime the user visit a page, the page url will be stored into an array session. I want to have 10 elements in the array only. So that 10 elements will save 10 latest visited page urls. Here is my codes :
<?php
$currentpageurl = $_GET['username'];
$urlarray=array();
$urlarray[] = $currentpageurl;
$_SESSION['pageurl']=$urlarray;
foreach($_SESSION['pageurl'] as $key=>$value)
{
echo 'The value of $_SESSION['."'".$key."'".'] is '."'".$value."'".' <br />';
}
?>
I tested the code, it always overwrite the element in the array with new visited page, thus it has only 1 element in the array. How to make it not to overwrite the element?
You are always overwriting the array with a new one here:
$urlarray=array(); // new empty array
$urlarray[] = $currentpageurl;
$_SESSION['pageurl']=$urlarray;
Instead use:
session_start();
// like #Kwpolska said, you probably miss that, so $_SESSION didnt work
is_array($_SESSION["pageurl"]) or $_SESSION["pageurl"] = array();
// fix for your current problem
$_SESSION['pageurl'][] = $currentpageurl;
// This appends it right onto an array.
$_SESSION["pageurl"] = array_slice($_SESSION["pageurl"], -10);
// to cut it down to the last 10 elements
Simplest way to do this and keep just the last 10 entries will be to create your initial array with the correct size (via array_fill()). Then we can push new items onto the beginning of the array and pop old items off the other end using array_unshift() and array_pop().
session_start();
// Initialise URL array with 10 entries.
if (empty($_SESSION['pageurls'])) {
$_SESSION['pageurls'] = array_fill(0,10,'');
}
function trackPage($url) {
array_unshift($_SESSION['pageurls'],$url);
array_pop($_SESSION['pageurls']);
}
Make sure the above code always runs first. Then you can pass new URLs to the array when you want. So, perhaps something like:
trackPage($_SERVER['REQUEST_URI']);
You've ommitted session_start();. Working code (without trimming):
<?php
session_start();
$currentpageurl = $_GET['username'];
$_SESSION['pageurl'][] = $currentpageurl;
foreach($_SESSION['pageurl'] as $key=>$value) {
echo 'The value of $_SESSION['."'".$key."'".'] is '."'".$value."'".' <br />';
}
?>

Categories