Find a ( string ) value in a PHP array

Asked

Viewed 97 times

1

I’m having trouble finding a variable value inside an array Example: I have the information below in some array.

$dadosCli1 = array("cep:'000000'", "cidade: 'sao paulo'", "rg: '00.000.000.-00'", "estado: 'sp'");

$dadosCli2 = array("rg:'00.000.000.-00'", "cidade: 'sao paulo'", "cep: '0000000'", "estado: 'sp'");

And so successively, the client data is cluttered within the arrays, but accurate of the card information, regardless of their positions within the array.
I’m starting in php now.

4 answers

1

You can format this array to access the keys directly. The way your values are you will still have to format the values.

$dadosCli1 = array("cep:'000000'", "cidade: 'sao paulo'", "rg: '00.000.000.-00'", "estado: 'sp'");
foreach( $dadosCli1 as $key => $val )
{
    list( $key1 , $val1 ) = explode( ':' , $val );
    $arr[ trim( $key1 ) ] = trim( $val1 );
}

Basically it will make a loop in the array and using explode separate the key from the val to be able to access...

The result is:

Array
(
    [cep] => '000000'
    [cidade] => 'sao paulo'
    [rg] => '00.000.000.-00'
    [estado] => 'sp'
)

Just use $arr['cep'] that you get the correct value


As a suggestion from @Guilherme Nascimento; You can use limit

If limit is set, the returned array will contain the maximum of elements equal to limit with the last element containing the rest of the string.

More about explode

  • 1

    Use in the third parameter of explode the value 2 (ex: explode(':', $val, 2)), to avoid splitting the string into more pieces, if there is a ":" inside something, for example "'foo':'bar:baz'"... of course in the author’s current code seems expendable, but you can’t be sure :)

  • 1

    @Guilhermenascimento was in doubt whether the answer would be a palliative or a gambiarra to solve the problem rs. Your suggestion closes all loose ends rsrsrs []’s

1

Considering the data in this format, you can create a function to standardize the output.

$dadosCli1 = array("cep:'000000'", "cidade: 'sao paulo'", "rg: '00.000.000.-00'", "estado: 'sp'");

function organiza_dados(array $cliente){

    $dados_organizados = array();
    foreach($cliente as $dado){
        $e = explode(' :', $dado);
        $dados_organizados[$e[0]] = $e[1];
    }
    return $dadod_organizados;
}

Then when it comes to organizing just apply the function.

$cliente = organiza_dados($dadosCli1);

The data will then be accessible via $cliente["cep"], for example.

0

In addition to the mandatory approaches presented in the other responses, it is also possible to use a functional approach using the function array_reduce(), which reduces an array to a single value via an iterative process via callback, in this case exploding each element of the original array and recombining the fragments in an associative array.
Another way is with array_reduce() dividing the original array in two, one containing the keys the other the values, and combining them in an associative array with the function array_combine.

<?php

$dadosCli1 = array("cep:'000000'", "cidade: 'sao paulo'", "rg: '00.000.000.-00'", "estado: 'sp'");

$dadosCli2 = array("rg:'11.111.111.-11'", "cidade: 'campo grande'", "cep: '0000000'", "estado: 'ms'");


$res1 = array_reduce($dadosCli1, function($c, $i){
  $v = explode(':', $i, 2);
  $c[$v[0]] = $v[1];
  return $c;
}, []);

$res2 = array_combine(...array_reduce($dadosCli2, function($c, $i){
  $v = explode(':', $i, 2);
  $c[0][] = $v[0];
  $c[1][] = $v[1];
  return $c;  
}, [[],[]]));


echo $res1["cidade"];   //'sao paulo'
echo $res2["cidade"];   //'campo grande'

Test the code on Repl.it

The above solutions in function form:

function f1($arr){
  return array_reduce($arr, function($c, $i){
    $v = explode(':', $i, 2);
    $c[$v[0]] = $v[1];
    return $c;
  }, []);
}

function f2($arr){
  return array_combine(...array_reduce($arr, function($c, $i){
    $v = explode(':', $i, 2);
    $c[0][] = $v[0];
    $c[1][] = $v[1];
    return $c;  
  }, [[],[]]));
}
  • 1

    Same thing you told @Papacharlie: Use in the third parameter of explode the value 2 (ex: explode(':', $val, 2)), to avoid splitting the string into more pieces, if there is a ":" inside something, for example "'foo':'bar:baz'"... of course in the author’s current code seems expendable, but you can’t be sure :)

0

all right? To access a specific value in a @rray you must pass the key you want in some way. Since the data is cluttered, you should pass the name of the key you want to return in the following way:

$dadosCli1 = array("cep" => "000000", "cidade" => "sao paulo", "rg" => "00.000.000.-00", "estado" => "sp");
echo $dadosCli1['cidade'];

Note that I needed to change the way the data is in the array, indicating that the first data is the key and the second the content.

To learn more about arrays, see the official documentation on: https://www.php.net/manual/en/language.types.array.php

  • excellent solution, I adapted your model to solve the problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.