Check if element is in array, but exclude array's last element? - php

How to check if a string is already in array, but during checking exclude last element of that array? By now, I'm using a workaround with unset() and re-declaration like this:
$fkTableName = $fkTableArr[$colNr0];
unset($fkTableArr[$colNr0]);
if (!in_array($fkTableName, $fkTableArr))
// do sth
$fkTableArr[$colNr0] = $fkTableName;
but it seems pretty redundant to me.

Use array_slice() to slice the array and use it. The below code doesn't include the last element in the array.
array_slice($input, -1);
So your code becomes:
$fkTableName = $fkTableArr[$colNr0];
if (!in_array($fkTableName, array_slice($fkTableArr, -1)))
// do sth

If you want to not affect the array, try this:
if (in_array($fkTableName, $fkTableArr) && $fkTableName != end($fkTableArr)) {
// element in array, but not last item
}

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]);
?>

Remove first element from simple array in loop

This question has been asked a thousand times, but each question I find talks about associative arrays where one can delete (unset) an item by using they key as an identifier. But how do you do this if you have a simple array, and no key-value pairs?
Input code
$bananas = array('big_banana', 'small_banana', 'ripe_banana', 'yellow_banana', 'green_banana', 'brown_banana', 'peeled_banana');
foreach ($bananas as $banana) {
// do stuff
// remove current item
}
In Perl I would work with for and indices instead, but I am not sure that's the (safest?) way to go - even though from what I hear PHP is less strict in these things.
Note that after foreach has run, I expected var_dump($bananas) to return an empty array (or null, but preferably an empty array).
1st method (delete by value comparison):
$bananas = array('big_banana', 'small_banana', 'ripe_banana', 'yellow_banana', 'green_banana', 'brown_banana', 'peeled_banana');
foreach ($bananas as $key=>$banana) {
if($banana=='big_banana')
unset($bananas[$key]);
}
2nd method (delete by key):
$bananas = array('big_banana', 'small_banana', 'ripe_banana', 'yellow_banana', 'green_banana', 'brown_banana', 'peeled_banana');
unset($bananas[0]); //removes the first value
unset($bananas[count($bananas)-1]); //removes the last value
//unset($bananas[n-1]); removes the nth value
Finally if you want to reset the keys after deletion process:
$bananas = array_map('array_values', $bananas);
If you want to empty the array completely:
unset($bananas);
$bananas= array();
it still has the indexes
foreach ($bananas as $key => $banana) {
// do stuff
unset($bananas[$key]);
}
for($i=0; $i<count($bananas); $i++)
{
//doStuff
unset($bananas[$i]);
}
This will delete every element after its use so you will eventually end up with an empty array.
If for some reason you need to reindex after deleting you can use array_values
How about a while loop with array_shift?
while (($item = array_shift($bananas)) !== null)
{
//
}
Your Note: Note that after foreach has run, I expected var_dump($bananas) to return an empty array (or null, but preferably
an empty array).
Simply use unset.
foreach ($bananas as $banana) {
// do stuff
// remove current item
unset($bananas[$key]);
}
print_r($bananas);
Result
Array
(
)
This question is old but I will post my idea using array_slice for new visitors.
while(!empty($bananas)) {
// ... do something with $bananas[0] like
echo $bananas[0].'<br>';
$bananas = array_slice($bananas, 1);
}

Checking the first element of array, regardless of array indexes

I have a need to check if the elements in an array are objects or something else. So far I did it like this:
if((is_object($myArray[0]))) { ... }
However, on occasion situations dictate that the input array does not have indexes that start with zero (or aren't even numeric), therefore asking for $myArray[0] will generate a Notice, but will also return the wrong result in my condition if the first array element actually is an object (but under another index).
The only way I can think of doing here is a foreach loop where I would break out of it right on the first go.
foreach($myArray as $element) {
$areObjects = (is_object($element));
break;
}
if(($areObjects)) { ... }
But I am wondering if there is a faster code than this, because a foreach loop seems unnecessary here.
you can use reset() function to get first index data from array
if(is_object(reset($myArray))){
//do here
}
You could get an array of keys and get the first one:
$keys = array_keys($myArray);
if((is_object($myArray[$keys[0]]))) { ... }
try this
reset($myArray);
$firstElement = current($myArray);
current gets the element in the current index, therefore you should reset the pointer of the array to the first element using reset
http://php.net/manual/en/function.current.php
http://php.net/manual/en/function.reset.php

Help with getting first value of array in PHP

Stumped by this one:
I have a function that returns an array of folders in a given directory. When I iterate through the array, I can see all the items. However, if I try to print the first item, I get nothing:
function get_folders($dir) {
return array_filter(scandir($dir), function ($item) use ($dir) {
return (is_dir($dir.'/'.$item) && $item != "." && $item != "..") ;
});
}
$folders = get_folders(".");
$first_folder = $folders[0];
echo $first_folder; // returns blank.
Interestingly, if I don't filter out the "." and "..", then $first_folder does print ".". Can anyone explain this?
As noted in the manual: Array keys are preserved when using array_filter().
The keys are preserved from the call to scandir() which will include the . and .. directories, meaning your filtered array will start at 2 or more (whatever the key is for the first directory).
A simple fix would be to wrap the whole thing in array_values() to get the resultant array having keys starting from 0 and incrementing by one.
return array_values(array_filter(...));
If you don't actually care about the keys, then basic array functions could be of use like key or current.
From the array_filter manual:
Iterates over each value in the input array passing them to the callback function. If the callback function returns true, the current value from input is returned into the result array. Array keys are preserved.
So, scandir($dir) gets you an array with . at key 0, thus if you later filter . out, there will be nothing at key 0 in the result.
If you want to know what the first key of the resulting array is, try the array_keys function.
EDIT: actually, salathe's suggestion to use array_values is better in your case than getting the keys from array_keys.
can you print the folders and see if there is some key you can get the first folder with as opposed to selecting the index of zero? It seems lke $folders[0] would work unless the entries are stored with a different set of indexes / keys.
Try doing a
print_r($folders)
to see if it outputs your first folder and all other folders as expected with the corresponding indexes you're looking for.
array_filter preserves array keys, so if the first two elements have been removed, then the "new first" element has an index of 2. To convert that into an array indexed starting from 0, use array_values:
return array_values(array_filter(scandir($dir), function ($item) use ($dir) {
...
As others have said, array_filter preserves the keys in the array. Given that initially the item '.' has key 0, the filtered array ends up not having any item with key 0 (you can verify this with print_r($folders). So this line:
$first_folder = $folders[0];
ends up generating an E_NOTICE saying that there is no key 0 in the array (having notices turned on would alert you to the cause of the problem immediately, I highly recommend it) and giving $first_folder the value null.
To get the first value of the filtered array, regardless of key, use reset:
$first_folder = reset($folders);
if($first_folder === false) {
echo 'No folders!';
}
else {
echo 'First folder: '.$first_folder;
}

array_unshift() with empty array

I want to add an element to the beginning of an array, but this array might be empty sometimes. I've tried using array_unshift() but it doesn't seem to like empty arrays... should I simply check for the empty array and append the element manually, or does array_unshift() not mind empty arrays but I'm just being a klutz?
Here is my code at the moment:
$sids = array();
$sids = explode(",", $sid['sids']);
array_unshift($sids, session_id());
The contents of the $sids array are taken from a database and are comma separated values.
Thanks,
James
EDIT
I've managed to fix this now - sorry everyone!
Here's the updated code:
$sids = array();
if(!empty($row['sids']))
{
$sids = explode(",", $row['sids']);
}
array_unshift($sids, session_id());
If $sid['sids'] is empty, explode will return FALSE
Then $sids will be equal to FALSE
and the subsequent call to array_unshift will fail.
You should probably make sure $sids is an array before calling array_unshift.
Here's a way to do it:
if(!empty($sid['sids']))
$sids = explode(",", $sid['sids']);
else
$sids = array();
array_unshift($sids, session_id());
First off, your first line of code is pointless; explode always returns a value, whether it be an array or FALSE. You're guaranteed to overwrite that value once you call explode.
Secondly, your code should work. One minor edit I'd make is this:
<?php
$sids = array();
$sids = explode(",", $sid['sids']);
if(is_array($sids))
array_unshift($sids, session_id());
?>
Because (even though your code says otherwise, and that the PHP documentation says otherwise), explode may not always return an array.
Another piece of information that may be useful is whether or not there was any error being reported, and, if so, what the error was.
Best of luck!
array_unshift() accepts the array parameter by reference. This means it must actually be a variable, not an expression like array(). It also means it will modify the variable you pass, not return a new array with the element added. Here's an example to illustrate this:
$array = array();
array_unshift($array, 42);
var_dump($array); // Array now has one element, 42
$sids = explode(",", $sid['sids']);
if (!is_array($sids)) {
$sids = array();
}
array_unshift($sids, session_id());

Categories