I have a text document that has a list of names in it, each one on its own line. I want to be able to go through that file, and delete one particular name. So I'm trying to create an array with all the original names, have a loop go through that array and add all the names except the one that needs to be deleted to a new array. If I try to print the new array, it still contains all of the names including the one that needs to be deleted.
$Delete = "Pete";
$startingNames = file("names.txt");
$newNames = array();
foreach($startingNames as $name)
{
if(strpos($name, $Delete) == false) //If its not the one that needs to be deleted
{
$newNames[] = $name; //Add it to the new array.
}
}
In this case, strpos will return 0, which will be interpreted as false
. Instead, we need to use the triple-equals operator to confirm the type as well as the value.
strpos($name, $Delete) === false
This would also be a good time to use array_filter
. This function will allow you to run a 'filter function' over an array, creating a new array with only the values you want. For example:
<?php
$names = ['Dave', 'Pete', 'Alex', 'Mark'];
$delete = 'Mark';
$newNames = array_filter($names, function ($name) use ($delete) {
return strpos($name, $delete) === false;
});
print_r($newNames);