1

I have a variable and i want to check if it starts with 'pa_' how can I do that? i have tried this but it does not work

 $test_str = 'pa_';

 if(substr( $product_attribute['name'], 0, strlen($test_str) ) === $test_str) {
                              $pa_array[]= $product_attribute['name'];
 }

2 Answers2

1

Just check if pa_ is at the first position of the string

if (strpos($product_attribute['name'], 'pa_') === 0) {
    $pa_array[]= $product_attribute['name'];
}

Try dd($pa_array) within the if-block to see if you even put it in the array.
I quickly tried this and it worked.

ofmiceandmoon
  • 548
  • 2
  • 9
  • 30
  • Thanks. strangely even though i passed string(8) "pa_color" to it the $pa_array() is empty :( –  Sep 04 '19 at 10:24
0

Use strpos or access chars in a string by using an offset value:

 $paName = $product_attribute['name'];
 if($paName[0] . $paName[1] . $paName[2] == $test_str) {
     $pa_array[]= $paName;
 }
mgutt
  • 5,867
  • 2
  • 50
  • 77