creating a new array with an element removed - php

I have an array of elements, e.g. (apple, orange, grapes)
Say this is an array in a variable $fruit. I want to create a new variable $new_fruit, that removes the first element, $fruit[0]
I want to be able to do this
$new_fruit = unset($fruit[0]);
Of course I cannot, if I unset $fruit[0], then its removed from $fruit, and I need all elements to remain in the element $fruit. And create a new variable without the first element.

As an alternative to the simple:
$new_fruit = $fruit;
unset($new_fruit[0]);
You can omit more than just the first one by changing the second argument:
$new_fruit = array_slice($fruit, 1);

Related

How to remove a single element from a PHP session array?

I am having a php session array like
('10/01/2017, '13/02/2017', '21/21/2107')
Now how to add and element or remove an element from this array in O(1)
The easiest way is to get the value, remove the item, and set the session variable again.
$data = $_SESSION['array']; // Get the value
unset($data[1]); // Remove an item (hardcoded the second here)
$_SESSION['array'] = $data; // Set the session value with the new array
Update:
Or like #Qirel said, you can unset the item directly if you know the number.
unset($_SESSION['array'][1]);
Update 2
If you want to remove the element by its value, you can use array_search to find the key of this element. Note that if there are to elements with this value, only the first will be removed.
$value_to_delete = '13/02/2017';
if (($key = array_search($value_to_delete, $_SESSION['array'])) !== false)
unset($_SESSION['array'][$key]);
To delete and element from an array use unset() function:
<?php
//session array O
unset(O["array"][1]);
?>

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.

PHP pass array without selected index

how to slice an array to pass it to a function. I cannot use unset because I need that array further. I know I can copy whole array to variable, however it's quite big and don't thing it's efficient. My code:
$list = array(0=>2123, 2=>1231, 7=>123123,...);
unset($list[0]); //I can't do this because I still need whole $list
$seats = $allocatingClass->allocateSeats($seatsNumber, $list); //here I need to slice $key from $list and pass $list without reiterating
If you need to keep index 0, store it, rather than storing the entire array elsewhere:
$tmp = $list[0];
Then splice the array:
$list = array_splice($list,1,count($list));
Then pass it to your function:
$seats = $allocatingClass->allocateSeats($seatsNumber, $list);
Then, when you need it, put back the value to the array:
$list[] = $tmp;
Edit: if you actually need to put it exactly at index 0, then you may want to unset the index 0 of the array instead of splicing it. If you can, however, push it at the end of the array just follow what is written above.
To clearify, if you need to LATER push back the element to index 0, do
unset($list[0]);
instead of the splice...
And to put back the element, do:
$list[0] = $tmp;
However you do it, a copy will be made when passing the array (unless you pass it by reference).
either use splice. or create a copy and shift one value.
after sending the copy variable, you can unset it so it wont keeptaking its space.
Edit :
The above solution is also viable. Though I suggest you use:
$tmp = array_shift($arr);
doStuf($arr);
array_unshift($arr, $tmp);

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'];

Check field and rewrite to array Codeigniter

I need to truncate string and rewrite it back to array
I have got a function where I get data from data base
$data['about_text_list'] = $this->about_text_model->get_array();
I get these fields from data base : id, num, header, text, language
I need to strip_tags and truncate text with function word_limiter
foreach ($data['about_text_list'] as $items)
{
$data['about_text_list']['text'] = word_limiter($items['text'], 100);
$data['about_text_list']['text'] = strip_tags($items['text']);
}
in view I do foreach
<? foreach ($about_text_list as $line) : ?>
<td><?=$line['text']?></td>
<? endforeach; ?>
But I get error, please tell me how to do correct things like this...
In the loop in your controller, you're limiting the word count, then setting that to the value in the array. Then, you're overwriting that value with the strip_tags function. You're using both functions on the same value instead of using the altered values. (And I would strip the tags first, then limit the word count.)
You're also just overwriting the $data['about_text_list']['text'] value each iteration. I'm assuming this needs to be an array of 'text' values? I would create a new array with the updated content and merge your $data['about_text_list'] array with the new array.
Change that loop to this:
$newarray = array();
foreach ($data['about_text_list'] as $key => $value)
{
$item_text = $value['text'];
$altered = strip_tags($item_text);
$newarray[$key]['text'] = word_limiter($altered, 100);
}
$data['about_text_list'] = array_merge($data['about_text_list'], $newarray);
// here, you create a new empty array,
// then loop through the array getting key and value of each item
// then cache the 'text' value in a variable
// then strip the tags from the text key in that item
// then create a new array that mirrors the original array and set
// that to the limited word count
// then, after the loop is finished, merge the original and altered arrays
// the altered array values will override the original values
Also, I'm not sure what your error is (as you haven't told us), but make sure you're loading the text helper to give you access to the word_limiter function:
$this->load->helper('text');
Of course, this all depends on the structure of your array, which I'm guessing at right now.

Categories