Beginner needs a bit of help and a slap across the face.

I am trying to search an array but my search string is invalid. And I expect it to be, but don’t know how to correct it.

Here is a working example that I used:

<?php $a=array("a"=>"Dog","b"=>"Cat"); echo array_search("Dog",$a); ?>

And here is how I need it to work for my purpose:

$x = (“2”);
$y = (“2”);

$key = array_search(’$dog’, $a);
$dog = “Dog_” . $x . “_” . $y ;

print $key; //this doesn’t
print $dog; //this works
How do I make $dog a valid search string? So that when I search for it will return the number. Thank you!

First of all: where to do you define the variable $dog? It looks to be uninitialized.
Secondly: single quotes will not parse PHP variables:

$key = array_search($dog, $a);

This is a possible solution, or use double quotes if you want extra text in there. Best practice (if you ask me) is to keep PHP variables outside quotes whenever possible.

I fixed it but it seams I was wrong to use it this way in the first place.
It turns out I need to switch the places of the key and the value and look for the value while I have the key name.

I reversed the array so now the value and it’s key switched places:

<?php $a=array("Dog_2_2"=>'234'); $x = ("2"); $y = ("2"); $dog = "Dog_" . $x . "_" . $y ; ...
now I need to use the key $dog, which is a string formed from post data, and look for the respective value.
I tried the KEY function, as in the previous post but it uses ARRAY_SEARCH and therefore searches by value and not by key.

I need to print 234 from this array.

Just grab the value from the array with the index:

$x = ("2");
$y = ("2");
$dog = "Dog_" . $x . "_" . $y ;

  echo $a[$dog];
//do something.....

array_key_exists() will check the array to make sure the key is valid.

Thank you! It works great. I didn’t expect it to be so simple.

Sponsor our Newsletter | Privacy Policy | Terms of Service