PHP Array Search Returns Empty Key - php

I'm trying to use array_search to find the key of a value in an array, I have the following simple code:
$current_user_existing_shopping_bag_string = '1446784/-/3/-/£797.00(_)902982/-/4/-/£148.80(_) ';
$current_user_existing_shopping_bag_array = explode('(_)', $current_user_existing_shopping_bag_string);
$key = array_search($current_user_existing_shopping_bag_array, '902982');
echo $key;
However I have no idea why this doesn't return the key of the value in the array, it should though. I've been trying various solutions for hours now and still no luck.
Anybody able to give me a pointer why this doesn't return the key for the value in the array?
Thanks

It is because array_search compares strings using === operator, not regex or strpos of any kind.
You search for 902982 but string is 902982/-/4/-/£148.80, and therefore they are not equal in any way.
For what you want to achieve, you can use preg_grep:
$result = preg_grep('/' . preg_quote($search) . '/', $current_user_existing_shopping_bag_array);
Then you can get the keys you need from the resulting array.

Related

array_push won't give an array, prints out integer value

I'm doing a very simple php program with array_push, but it isn't working according to the documentation. Every time i try to print the value of the final array, it gives me an integer. Could someone please help me with this?
Here's my code:
<?php
$preArray = array('1','2','3','4','5','6','7','8');
$val = 10;
$array = array_push($preArray, $val);
print_r($array);
?>
This is what it outputs:
9
Thanks in advance for the help.
array_push() returns the new number of elements in the array. So if you're not interested in the number of elements in the array then just use:
array_push($preArray, $val);
The variable $preArray will contain the value pushed into it.
print_r($preArray);

How to find matching values in multidimentional arrays in PHP

I am wondering if anyone could possibly help?....I am trying to find the matching values in two multidimensional arrays (if any) and also return a boolean if matches exist or not. I got this working with 1D arrays, but I keep getting an array to string conversion error for $result = array_intersect($array1, $array2); and echo "$result [0]"; when I try it with 2d arrays.
// matching values in two 2d arrays?
$array1 = array (array ('A8'), array (9,6,3,4));
$array2 = array (array ('A14'), array (9, 6, 7,8));
$result = array_intersect($array1, $array2);
if ($result){
$match = true;
echo "$result [0]";
}
else{
$match = false;
}
if ($match === true){
//Do something
}
else {
//do something else
}
The PHP documentation for array_intersect states:
Note: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same.
So, the array to string conversion notice is occurring when PHP attempts to compare the array elements. In spite of the notice, PHP will actually convert each of the sub-arrays to a string. It is the string "Array". This means that because
array_intersect() returns an array containing all the values of array1 that are present in all the arguments.
you will end up with a $result containing every element in $array1, and a lot of notices.
How to fix this depends on exactly where/how you want to find matches.
If you just want to match any value anywhere in either of the arrays, you can just flatten them both into 1D arrays, and compare those with array_intersect.
array_walk_recursive($array1, function ($val) use (&$flat1) {
$flat1[] = $val;
});
array_walk_recursive($array2, function ($val) use (&$flat2) {
$flat2[] = $val;
});
$result = array_intersect($flat1, $flat2);
If the location of the matches in the arrays is important, the comparison will obviously need be more complex.
This error(PHP error: Array to string conversion) was caused by array_intersect($array1, $array2), cause this function will compare every single element of the two arrays.
In your situation, it will consider the comparison as this: (string)array ('A8') == (string)array ('A14'). But there isn't toString() method in array, so it will incur the error.
So, if you want to find the matching values in two multidimensional arrays, you must define your own function to find it.

How to get the position of the string in an array

I want to know why array_search() is not able to get the position of the string in the following array
MY Code
$row1['infopropiedades'] ="Dirección<>#Fotos<>SALTEST.ANUNCIO.IMAGENES.IMAGEN.IMAGEN_URL#Fotos Description<>SALTEST.ANUNCIO.DESCRIPCION#Map<>#Youtube URL<>#Titulo<>SALTEST.ANUNCIO.TITULO#Descripción<>SALTEST.ANUNCIO.DESCRIPCION#Detalles específicos<>#Telefono<>SALTEST.ANUNCIO.TELEFONO#Celular<>SALTEST.ANUNCIO.TELEFONO#Terreno<>SALTEST.ANUNCIO.TERRENO#Construcción<>SALTEST.ANUNCIO.CONSTRUCCION#Venta<>SALTEST.ANUNCIO.MONEDA#Alquiler<>";
$x= explode("#",$row1['infopropiedades']);
print_r($x);
echo $key = array_search('Fotos Description', $x);
if($key!=0)
{
$v = explode('<>',$x[$key]);
echo $Fotos_Description = $v[1];
}
Thanks in advance
array_search() is looking for the exact string not a partial match. Here is a quick way to get it:
preg_match('/#Fotos Description<>([^#]+)#/', $row1['infopropiedades'], $v);
echo $Fotos_Description = $v[1];
preg_grep was made for searching arrays and will return the results in an array. A combination of key() and preg_grep() will return the key you are looking for.
echo $key = key(preg_grep("/^Fotos Description.*/", $x));
As others pointed out, array_search only matches if the value is equal.
Since your needle is only a part of the whole haystack that each array element contains, array_search won't work. You can loop through all the values and find what you are looking for
foreach($x as $key=>$haystack)
{
if(stristr($haystack,'Fotos Description')!==FALSE)
{
$v = explode('<>',$haystack);
echo $Fotos_Description = $v[1];
}
}
Fiddle
Because array_search just searches for an exact match. So you have to iterate over the whole array and check if the value has this string
or you could use array_filter with a custom callback function for example

Remove blank and duplicate variables from query string in PHP

I'm looking for a simple function which will remove blank or duplicate variables from a query string in PHP. Take this query string for example:
?input=timeline&list=&search=&type=&count=10&keyword=hello&from=&language=en&keyword=&language=en&input=timeline
As you can see there are two input=timeline and the language and keyword variables appear twice- once set and once not. Also there are lots of variables that are blank- list, search and type.
What function would clean the URL up to make:
?input=timeline&count=10&keyword=hello&from=&language=en
?
I've found functions that remove queries, or certain variables, but nothing that comes close to the above- I can't get my head round this. Thanks!
I'd suggest simply taking advantage of PHP's parse_str, but as you mentioned, you've got multiple keys that are the same and parse_str will overwrite them simply by the order they're given.
This approach would work to favor values that are not empty over values that are, and would eliminate keys with empty values:
$vars = explode('&', $_SERVER['QUERY_STRING']);
$final = array();
if(!empty($vars)) {
foreach($vars as $var) {
$parts = explode('=', $var);
$key = $parts[0];
$val = $parts[1];
if(!array_key_exists($key, $final) && !empty($val))
$final[$key] = $val;
}
}
If your query were input=value&input=&another=&another=value&final=, it would yield this array:
[input] => value
[another] => value
...which you could then form into a valid GET string with http_build_query($final).
"?" . http_build_query($_GET) should give you what you want. Since $_GET is an associative array any duplicate keys would already be overwritten with the last value supplied in the query string.

Extract parts from Array keys in php and combine them

i have also got a similar question. I have an array where i need to extract parts from the keys of array and combine them. can you please suggest the best way for it.
$myarray=Array(
[0]=>'unwanted text'
[1]=>'unwanted+needed part1'
[2]=>'needed part2'
[3]=>'needed part3'
[4]=>'unwanted text'
)
how can i extract only the needed parts and combine them. Thanks a lot ahead.
Not exactly sure if this does what you want, but looping and copying to a new array should basically achieve your result (once you clarify how you decide which part of the strings are needed or unwanted)
$myarray = array(…);
$new_array = array();
$unwanted = 'some_string';
foreach($myarray as $k => $v) {
$new_value = preg_replace("/^$unwanted/", '', $v); # replace unwanted parts with empty string (removes them);
if(!empty($new_value)) { # did we just remove the entry completely? if so, don't append it to the new array
$new_array[] = $v; # or $new_array[$k] if you want to keep indices.
}
}
Assuming you want to join array entries and have a string as result, use the implode function of PHP: $string = implode(' ', $new_array);
The functions you are after, depending on what you want to do, will be a combination of the following: array_splice, array_flip, array_combine.
array_splice()
allows you to extract part of an array by key offset. It'll permanently remove the elements from the source, and return these elements in a new array
array_flip()
Turns keys into values and values into keys. If you have multiple identical values, the last one has precedence.
array_combine() takes two parameters: an array of keys, and an array of values, and returns an associative array.
You'll need to provide more info as to what you want to do, though, for my answer to be more specific.

Categories