0

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

3
  • 2
    Because Fotos Description is not in the array. Fotos Description<>SALTEST.ANUNCIO.DESCRIPCION is. Commented Apr 8, 2015 at 15:51
  • 1. What is your goal with this code? 2. You don't have an element with Fotos Description Commented Apr 8, 2015 at 15:52
  • Actually I am trying to save the string that is related with Fotos Description in the variable $Fotos_Description. Commented Apr 8, 2015 at 15:53

4 Answers 4

2

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];
Sign up to request clarification or add additional context in comments.

Comments

2

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.

2 Comments

I love preg_grep but the title here is misleading. They don't really want the position, they want a string after a string.
@AbraCadaver, yes, I didn't read into the code as much as you did. Thanks for replying.
1

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.