1

Need some help exploding this PHP array and assign it a variable to each.

in Splits i have two inputs. a first name and last name.
example.

Chris Moreno. I want to be able to grab that and endpoint and exploding it and pass them into a variable.

(endpoint) api.org/endpoint?filter= Chris Moreno

$splits = explode(' ', $filter);

foreach ( $splits as $key => $literalFilter){}

fName = chris
lName = moreno

Ive tried a could of things but i am not able to do it. has someone ran into this before?

if i do vardump at $splits i get the following;

array(2) {
  [0]=>
  string(5) "chloe"
  [1]=>
  string(6) "moreno"
}
4
  • I'll give you half the answer: $fname = $splits[ 0 ]; Commented Jun 17, 2019 at 13:12
  • I am already using the variable $filter to do that. ($filter = $request->get('filter');). when i do that alone I get "Chris Moreno" as one string. My ultimate goal is to be able to split them so i can allow users to search by first and last name via a msyql query. Commented Jun 17, 2019 at 13:12
  • wait, did I misunderstand the question entirely? (based on last comment in chain) Commented Jun 17, 2019 at 13:14
  • @treyBake no, your right on the money, I think i just fazed out that i couldn't see that. I like the list as well. Thank you. do you know Doctrine fairly well? my next step to do a doctrine query so that i can search by first and last name now that i have those endpoints in variables Commented Jun 17, 2019 at 13:19

1 Answer 1

1

You can use list():

list — Assign variables as if they were an array

example with your code:

list($first, $last) = explode(' ', $filter);

Essentially, you list out varnames for the array indexes to follow, so if you had an array of:

Array => [1, 4, 5];

you could do:

list($foo, $bar, $foobar) = $array;
echo $foo. ' ' .$bar. ' '.$foobar; # will output 1 4 5

full docs: https://www.php.net/manual/en/function.list.php

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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