Delete element from array if not found - php

I have some code I created which is supposed to see if something exists in an array of strings. If it does not exist, I want to delete that element of the array. I thought we do this with unset, but it doesnt seem to be working. Mind helping?
echo '<br>size of $games before end-check: '.sizeof($games);
foreach ($games as $game) {
$game_end_marker = "body = (game)#";
$game_end_pos = strpos($game, $game_end_marker);
if ($game_end_pos !== false) {
echo "<br>end of game found";
}
else {
echo "<br>end of game not found. incomplete game";
unset($game);
}
}
echo '<br>size of $games after end-check: '.sizeof($games);
output:
size of $games before end-check: 2
end of game found
end of game not found. incomplete game
size of $games after end-check: 2

Because you unset the variable $game, not the element in the array. Try this:
echo '<br>size of $games before end-check: '.sizeof($games);
foreach ($games as $index => $game) {
$game_end_marker = "body = (game)#";
$game_end_pos = strpos($game, $game_end_marker);
if ($game_end_pos !== false) {
echo "<br>end of game found";
}
else {
echo "<br>end of game not found. incomplete game";
unset($games[$index]);
}
}
echo '<br>size of $games after end-check: '.sizeof($games);

You have to unset the index of game.
foreach ($games as $key => $value) {
// all your logic here, performed on $value
unset($games[$key]);
}

This merely unsets your local reference to the element. You need to be referring directly to the array.
foreach($games as $key => $game)
unset($games[$key]);

That won't work: foreach creates a new variable, copying the old one. Unsetting it will do nothing to the original value. Likewise, making it a reference won't work either, since only the reference would be deleted.
The nicest way to do this would be with array_filter:
$games = array_filter($games, function($game) {
$game_end_marker = "body = (game)#";
$game_end_pos = strpos($game, $game_end_marker);
if ($game_end_pos !== false) {
echo "<br>end of game found";
return true;
}
else {
echo "<br>end of game not found. incomplete game";
return false;
}
});
This uses the anonymous function syntax introduced in PHP 5.3. If the function returns true, the element is kept; if it returns false, the element is removed.

You can also call by reference:
foreach($games as &$game) {
unset($game);
}
In this way you can also change $game (eg. $game .= " blah";) and the original array will be modified.

You can use array_splice in conjunction with an incrementally-increasing index variable to remove the current item from the array:
$index = 0;
foreach ($games as $game) {
$game_end_marker = "body = (game)#";
$game_end_pos = strpos($game, $game_end_marker);
if ($game_end_pos !== false) {
echo "<br>end of game found";
}
else {
echo "<br>end of game not found. incomplete game";
array_splice($games, $index, 1);
}
$index++;
}

Related

how to use the in_array function, that is storing a variable from an input field

I am trying to check if a value already exists in an array with the in_array function but it is not working. When i assign the $companyalis variable to a string, lets say "Bay" it works. Please how can i solve this issue. Note: the $alias contains a value from an input field.
$companyalis = strtoupper($alias);
if (is_array($responses)) {
$data = [];
foreach ($responses as $val) {
$data[] = $val['alias'];
}
if (in_array($companyalis, $data)) {
echo "Alias is already defined";
}else {
echo "Alias does not exist";
}
}
}
If I understood your question correctly
$companyalis = strtoupper($alias);
if (is_array($responses)) {
$data = [];
foreach ($responses as $val) {
$data[] = $val['alias'];
}
if (in_array($companyalis, array_values($data))) {
echo "Alias is already defined";
} else {
echo "Alias does not exist";
}
}
$aliasList[] = "Other";
$aliasList[] = "manY";
$aliasList[] = "someTime";
$test = "Many";
if(in_array(strtolower($test),array_map('strtolower',$aliasList))) echo "Find";
else echo "Not Find";
I think this code can help you if I understood your question correctly.
The principle is to pass the search string in lowercase as well as all the elements of the array. Via the "strtolower" function applied thanks to "array_map" (thus on the whole array)

Foreach last item gets methode

Guys I have an array with objects,
I want the last item in the foreach loop do something else then the rest.
How do I archive that?
if(sizeof($testDup) > 3){
} else {
foreach ($testDup as $d) {
}
}
$test array(3)
432 => test_id -> 21
431 => test_id -> 21
435 => test_id -> 21
This will process the array of objects and do something else with the last element:
$data = '';
$arrayWithObjects = array(
(object)array('test1', 'test2'),
(object)array('test1', 'test2'),
(object)array('test1', 'test2'),
);
foreach ($arrayWithObjects as $object) {
// Can't get next in the array, so is last element
if (!next($arrayWithObjects)) {
// Process last element
$data .= $object->{1};
} else {
// Process all other elements
$data .= $object->{0};
}
}
var_dump($data); // "test1test1test2"
you can compare the current one with the end():
class Test {
public function __construct(private string $name) {}
public function read(): string {
return sprintf('%s: hurray', $this->name);
}
public function readLast():string {
return sprintf('%s: am I last?', $this->name);
}
}
$array = [
new Test('first'),
new Test('second'),
new Test('third'),
new Test('fourth'),
];
foreach( $array as $object ){
if($object === end($array)) {
echo $object->readLast().PHP_EOL;
}else{
echo $object->read().PHP_EOL;
}
}
As an alternative to checking if the current item is the last one (which the other answers show), you could use array_slice() to get the start of the array to loop over and then end() to get the last element of the array.
$data = [/*...*/]
foreach ($item as array_splice($data, 0, -1, true) {
$item->foo();
}
if (($item = end($data) !== false) {
$item->bar();
}
In my opinion, this code is easier to read (and metrics like cyclomatic complexity agree) than the nested if $item === end($data) check. If the same is true on your specific case will depend on what, exactly is in the loop and how much of it is different.
In addition, if your array is large, this approach may offer (slightly) better performance (but if your array is large and a small performance difference is important, don't take my word for this - benchmark both solutions with read data).
It's so easy: When the loop is finished, you still got the last element!!
if (!empty($arr)) {
foreach ($arr as $item) {
; // Do something with $item
}
// Here you still got last $item
echo var_export($item, true);
}

PHP Json only a first result

My issue is that when I use foreach trough my JSON commands it will only give the first command. In this case HELP but not the second one that is Test.
How can I fix this?
PHP:
echo "Commands:<br>";
$json = file_get_contents("App/cmd/commands.json");
$register = json_decode($json, true);
$command = $_GET["c"];
foreach ($register['commands'] as $key => $value){
echo $key;
if($command == $key)
{
echo "Found!";
return;
}
if(isset($register["commands"][$key]["alias"])){
echo " Has Aliases<Br>";
$aliases = explode(",", $register["commands"][$key]["alias"]);
foreach ($aliases as $alias)
{
if($command == $alias)
{
echo "Found!";
return;
}
}
}
echo "Not Found!";
return;
}
My Json:
{"help":"value","commands":{"help":{"function":"test"},"test":{"function":"test"}}}
It is because you set
echo "Not Found!"; return;
in the loop so there is no chance for second iteration. That code should be after loop not inside.
Because you have return; everywhere. Then you can't have a second iteration, because you always finish the process. Remove the return according to your logic to have a second iteration and make proper refactor to your code, to make it functional.

Unknown php unset error

I have problem in deleting an element of array. Look:
<?php
session_start();
$i = 0;
$expected = $_GET['name'];
foreach($_SESSION['chart'] as $name)
{
if($name==$expected)
{
break;
}
$i++;
}
unset($_SESSION['chart'][$i]);
echo count($_SESSION['chart'])." ".$expected." ".$i;
//echo "<script>history.go(-1);</script>";
?>
I'm getting this output: 3 name 2.
I know that element in array exists with name 'name', but I can't unset it. Please help me.
Why not let PHP do the search?
<?php
session_start();
$key = array_search($_GET['name'], $_SESSION['chart']);
if ($key !== false) {
unset($_SESSION['chart'][$key]);
}
because you call unset out of foreach
try :
foreach($_SESSION['chart'] as $name)
{
if($name==$expected)
{
unset($name);
}
$i++;
}
You can make your intent clearer by using this form of foreach
foreach($_SESSION['chart'] as $idx=>$name)
{
if($name==$expected)
{
unset($_SESSION['chart'][$idx]);
break;
}
}
However, Till Helge Helwig's solution is better for this particular problem, but it's worth being aware that you don't need to maintain your own 'key' variable when using foreach.

Replace value in array doesn't work

I'm going crazy, spent a couple of hours trying different methods in replace values in arrays, but I can't get it to work.
foreach($potentialMatches as $potentialKey)
{
$searchKeywordQuery = "SELECT keyword, id FROM picture WHERE id='$potentialKey'";
$searchKeywords = mysql_query($searchKeywordQuery) or die(mysql_error());
while ($searchKeyWordsRow = mysql_fetch_array($searchKeywords))
{
$keyword = $searchKeyWordsRow['keyword'];
$pictureKeywordArray[$searchKeyWordsRow['id']]['keywords'] = explode(",", $keyword);
$pictureKeywordArray[$searchKeyWordsRow['id']]['match'] = 4;
}
}
foreach($pictureKeywordArray as $key = > $picValue)
{
foreach($picValue['keywords'] as $key = > $picIdValue)
{
if ($picIdValue == $searchIdKey)
{
echo $picValue['match'];
$picValue['match']++;
echo $picValue['match'];
}
}
}
foreach($pictureKeywordArray as $key = > $picValue)
{
echo $picValue['match'];
}
I'm novice as you can see, When I echo the picValue['match'] in the foreach loop it gives me a correct value after "++". But then below when I call the array again it gives me the value of 4 instead of 5 as intended. Thanks in advance for any help with this.
Cause you work with the item copy in first case try $pictureKeywordArray[$key]['match'] instead of $picValue['match']
In that second foreach you need to call it by reference:
foreach($pictureKeywordArray as $key => &$picValue)
{ //^-- `&` makes it by reference
foreach($picValue['keywords'] as $key => $picIdValue)
{
if ($picIdValue == $searchIdKey)
{
echo $picValue['match'];
$picValue['match']++; //now updates what you want it to update
echo $picValue['match'];
}
}
}
foreach works on a copy of the data. You must use a reference to modify the original:
foreach ($foo as $i => &$f)
{
$f++;
}
unset($f); // important to do this if you ever want to reuse that variable later

Categories