foreach ($myarray as $value)
{
if (strpos($value,'mysearchstring'))
//add this $value to new array here
}
Also where would the second array need to be declared and how?
foreach ($myarray as $value)
{
if (strpos($value,'mysearchstring'))
//add this $value to new array here
}
Also where would the second array need to be declared and how?
To avoid warnings, the second array should be declared like so
$newArray = array();
This could be incorporated into your code like so
$newArray = array();
foreach ($myarray as $value){
if (strpos($value,'mysearchstring') !== false ){
$newArray[] = $value;
}
}
Your original code contained an error.
strpos returns and false
if it doesn't contain the needle, else it returns the index of the occurrence. So strpos($value,'mysearchstring')
will return 0 if $value
starts with 'mysearchstring'
. As PHP will convert 0
to false
and visa versa, it will not get added to the array if we use the standard comparisons, so we need to explicitly check that it is false without type conversion (converting 0
to false
for example). To do this we use !== (Note the two =
)s. This is represented in the code above.
For more information on comparison operators in php, see the documentation.
EDIT
Regarding the commend and usage of []
, it ads the new element to the end of the array
The documentation states that:
if no key is specified [in the square brackets], the maximum of the existing integer indices is taken, and the new key will be that maximum value plus 1. If no integer indices exist yet, the key will be 0 (zero).
So if we have an array
$arr = array(5 => 1, 12 => 2);
//doing this
$arr[] = 56;
//is exactly the same as doing
$arr[13] = 56
//As the maximum integer key is 12, so the new key is 13