Skip to content
Advertisement

Getting values to compare from a Explode Array of Strings

I have this string that I’m Getting from a Mysql Result:

Result1:

1/test3&2/test4&

Then, I have some ID from another mysql Result like this:

Result2:

$id = $row['id'];

Then I’m using an Explode in order to separate Result1:. Like I’m Getting this:

$nota3 = explode("&", $nota);

1/test3&
2/test4&

Now, I’m doing I’m using a foreach and then using another explode to separate the string by “/” delimiter.

foreach ($nota3 as $key) {

$nota4 = explode("/", $key);

}

The Result of this its something like this (for the firsts foreach iteration):

array(2) {
  [0]=>
  string(1) "1"
  [1]=>
  string(5) "test3"
}

Ok, So I cannot Compare nota4[0] with $id from Result2:

Things that I’ve Tried:

  • Using if and verify every type, converts nota4[0] a $id to string

  • Try to use in_Array

  • Try to use strcmp($var1, $var2)

I’m Missing something but I really dont know what.

Also, when I tried I cant put nota4[0] into a html String like

$nota5= nota4[0];

echo "<p id='mic' class='text-dark bg-warning'>".$nota5."</p>";

Maybe its something silly but I tried everything without success.

Advertisement

Answer

You can make sure both are strings and trim and use a strict operator – even if it seems they are already that

$result1 = "1/test3&2/test4&";
$result2 = "1";

$id = trim((string) $result2);
foreach ($nota3 as $key) {
  $nota4 = explode("/", $key);
  if (trim((string) $nota4[0]) === $id) {
     //...
  }
}

Here’s another way to go about it. This will set up $result1 (or you can rename it) to become an associative array of key/value pairs, allowing you to loop through and compare a value like $result2 with a key id in the $result1 array. Example link included.

<?php

$result1 = "1/test3&2/test4&";
$result2 = "1";

$result1 = array_map(function ($a) { 
    $tmp =  explode("/", $a);
    return array('id' => $tmp[0],'name' => $tmp[1]);
}, array_filter(explode("&", $result1)));

print_r($result1);

now to get $result2

foreach ($result1 as $item) {
  if ($item['id'] == $result2) {
    // $value 
  }
}

Output of result1

[0] => Array
    (
        [id] => 1
        [name] => test3
    )

[1] => Array
    (
        [id] => 2
        [name] => test4
    )

https://www.tehplayground.com/1436vTBhUOYx9MNX

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement