Page 1 of 1

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

Posted: Wed Jan 16, 2008 3:12 am
by Jaret
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:

Code: Select all

<?php
$a=array("a"=>"Dog","b"=>"Cat");
echo array_search("Dog",$a);
?>
And here is how I need it to work for my purpose:

Code: Select all

<?php
$a=array("234"=>"Dog_2_2");
$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!

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

Posted: Wed Jan 16, 2008 3:26 am
by crystal ship
$key = array_search('$dog', $a);
Here, $dog is a variable name and cannot be kept inside ' '. By doing so you are searching for the string $dog in array $a and define $dog before you search it in the array $a.

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

Posted: Wed Jan 16, 2008 5:28 am
by devendra-m

Code: Select all

 
 <?php
 $a=array("234"=>"Dog_2_2");
 $x = ("2");
  $y = ("2");
 $key = array_search('$dog', $a);
 $dog = "Dog_" . $x . "_" . $y ;
 print $key; //this doesn't
 print $dog; //this works
 ?>
instructions are not in correct order.

corrected

Code: Select all

   <?php
    $a=array("234"=>"Dog_2_2");
    $x = ("2");
    $y = ("2");
    $dog = "Dog_" . $x . "_" . $y ;
    $key = array_search($dog, $a);
    print $key; //this doesn't
   print $dog; //this works
   ?>

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

Posted: Wed Jan 16, 2008 5:49 am
by Jaret
Thank you very much guys, but it seams I was wrong to use this function 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:

Code: Select all

<?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.

I managed to print it with:

Code: Select all

$arr = array( "tile_1_2_left" => "352" );
foreach ($arr as $key => $value) { print $value; }
But it's not helping because I never specified a key name.