Make A New Array From An Old Array (Excluding 1 Array Element)
Hi,
What I am trying to achieve is...
• I have an array of web site names (like, siteA, siteB, siteC, siteD, siteE, etc), for example.
• I have a variable, like $site = "siteC"
• Now, the function will create a NEW array from the WHOLE contents of the old array, and only EXCLUDE the variable array element from the old array element list.
For example usage...
"newArray($site)" function will print all the array elements of "oldArray()", and will NOT include the element of $site (that is 'siteC' in this example). So, the new array will contain siteA, siteB, siteD, siteE, etc.
I don't know, how to exclude an element from a particular array. That's why, I am not being able to make this simple function.
Thanks both of you, NeverMind and nova912. But, I am confused as which one to choose? Both of these codes will produce the exact same result? My array will have the web site names, not the numbers only. Please let me know, which one is better, faster and easier? I guess, the first one.
The problem with Nova's code is, if there are values in the array like "site", "site2", etc.. and you want to remove "site"... it'd remove site2 as well, because stripos() wouldn't return false. So a mix of both solutions should work:
PHP Code:
function array_remove_val($array, $value)
{
unset($array[array_search($value, $array)]);
return $array;
}
Thanks for the detailed help! I was about to use the first code, done by NeverMind, since it's very simple! Do you think, it will show wrong output, if the elements are different in looks, as you have said, like 'site' and 'siteB'? You said it for nova912's code, but didn't say about NeverMind one. Please let me know.
Sorry I couldn't elaborate more. I clicked on the edit button to explain but my laptop died on me
Anyway, the code provided by me, enhanced by Nico, will do case-sensitive search and if the value you are searching for doesn't exist, it will not notify you but rather a php notice will generated. So a final enhanced version would be:
PHP Code:
function array_remove_val($array, $value) { if (!in_array($value, $array)) return false;